It seem to be a silly question and possibly a dupe, but I couldn't find a good solution for a while, so finally dare to ask.
I want to place an <svg>
element inside an html document and satisfy the following requirements:
- Image is placed as an
<svg>
html5 element, not an external svg-file. (Actually, I want to dynamically generate it with D3.js.) - Image is placed in the center of the screen, both vertically and horizontally.
- Actual size of the image should not exceed some predefined value (like
15cm × 15cm
). - If either current screen's width or height is less then
15cm
, image should be scaled (preserving aspect ratio) in such a way it fit to screen. No parts of the image should be clipped. Image should be placed in the center.
It's basically the same requirements as described in this article. It says that I should use preserveAspectRatio="xMidYMid"
, but gives no example on how to do it and how does it correspond to other tricks described in the article. This article suggests preserveAspectRatio="xMidYMid meet"
, but again I wasn't able to reproduce the examples provided there to meet all my requirements.
My current code is like this but it does not fit in height and does not center vertically.
.svg-container {
height:100%;
width:100%;
max-height:15cm;
max-width:15cm;
margin: 0 auto;
}
<div class="svg-container">
<svg id="picture" preserveAspectRatio="xMidYMid meet" viewBox="0 0 100 100">
<circle cx=50 cy=50 r=50></circle>
</svg>
</div>
You still want aligment vertical? look this
The flexbox solution would be my first choice. Since someone else has already answered with that idea I came up with this different approach.
Basically it is the absolute centering technique and rely on absolute position and auto margin to center the element.
The following works if the aspect ratio of the SVG is a given. If the aspect ratio of the SVG is dynamic, you have to use JavaScript, I believe.
This snippet works in modern browsers and takes full advantage of the relatively new
vmin
viewport-percentage length. Browser support is pretty good. For horizontal and vertical centering, the flexbox layout mode is leveraged. Again, browser support is pretty good.The trick is that the dimensions of the SVG are set relative to either the width or the height of the screen, whichever is smallest. This means that even when we would set it to be
100vmin
, the SVG is guaranteed to fit the screen (but barely). To enforce maximal dimensions, good oldmax-width
andmax-height
are used, exactly as they are intended to be used.Try this css:
here is the result: https://jsfiddle.net/twe9jfkf/
is this what you try to achieve?
Have you tried adding the image as a background to your svg-container?
Rather than css, you may want to try using svg's width/height, and viewBox computed via getBBox() A basic example is shown below: