This simple piece of html:
<div style="background:blue">
<svg width="40" height="40" style="background:red"></svg> some text
</div>
You can see that the svg is 40px
but the surrounding div is 44px
high (tested on chrome).
Why. And how to make the surrounding div respect the size of the SVG without an explicit height
on the surrounding div and keeping the layout svg+text
in a single line?
The explanation is that inline-block elements (like <svg> and <img> ) sit on the text baseline. The extra space you are seeing is the space left to accommodate character descenders (the tail on 'y', 'g' etc).
The real reason for all your extra whitespace is simple. In your SVG you have specified a viewBox of "0 0 600 400" (a 600x400 area with origin at 0,0), but your drawing only occupies a much smaller region in the middle of that. If you fix the viewBox, the graphic will conform to the size you give to the SVG.
This is done using the attribute "preserveAspectRatio" and setting it to "none". Hopefully this helps some of your understanding of SVGs, as they're a really useful tool! Show activity on this post. If you want the SVG to stretch to the entire box, put preserveAspectRatio="none" on the root <svg> element.
The svg
element here has display: inline
, thus is treated like text. It thus also observes the line-height
property which controls how much extra vertical space each line gets. For readability reasons we don't cram lines directly together.
Switching to display: block
on the svg
makes the div
fit exactly, as does setting line-height: 0
on the div
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With