سؤال

I would like to contain page logo and nav in the same header container - logo on the left, nav container on the right. How to make SVG logo embedded inline properly scale to always fill 100% of its container (header) height and auto scale width - at the same time staying on the left of the container? (Do I need separate <div> to wrap <svg> container?)

Probably I have to set svg viewBox property, but I'm not sure about how to do it to be sure that it will be responsive and render properly in different resolutions)?

My code:

HTML:

<header id="page-header">

    <svg id="logo" 
         xmlns="http://www.w3.org/2000/svg">
         <path d="..."/><g></g>
    </svg>

    <nav id="page-nav">
          <a href="...">...</a>
          ...
    </nav>

</header>

CSS:

#page-header {
    height: 9em;
    padding: 0;
    margin: 0 0 6em 0;
}

#logo {
    padding: 0;
    width:600px;  //not working at all.

    vertical-align:top;
    float:left;

    display:inline-block;
}

#page-nav {
   float:right;
   ...
}
هل كانت مفيدة؟

المحلول

You should set the viewBox attribute first, and then make all of your dimensions within your svg relative to that. When you assign height and width (whether in your svg tag or in your css) you are adjusting the size of the svg bounding box, not the size of the elements within it. By setting a viewBox you let the browser know that you want the image to be contained within a certain bounding box, and then when you then adjust the width or height, it will be re-scaled accordingly.

The viewBox attribute takes four space-separated values x y w h where x is the x-coordinate of the left side of the bounding box, y is the y-coordinate of the top of the bounding box and w and h are the width and height of the bounding box.

If you want a square bounding box for your logo, you could do something like this:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
  <!-- your svg elements -->
</svg>

Then everything would be sized relative to a 100x100 bounding box, so if you wanted a circle in the center, with the same width as the bounding box, you would just do:

<circle cx="50" cy="50" r="50" fill="red"></circle>

Then if you used your css to make the width: 100%;, your circle would be the width of your container rather than 50px.

Here's a fiddle that shows how changing each value of the viewBox affects the output. Hope that helps.

نصائح أخرى

You can indeed scale the svg image with css, take a look at this page, where it is explained well with many examples. http://soqr.fr/testsvg/embed-svg-liquid-layout-responsive-web-design.php

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top