Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the containing div for svg taking more space [duplicate]

Tags:

html

css

svg

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?

like image 668
basarat Avatar asked Sep 27 '16 05:09

basarat


People also ask

Why is there extra space in SVG?

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).

Do SVGs take up space?

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.

How do I get rid of SVG padding?

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.


1 Answers

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.

like image 186
Joey Avatar answered Nov 16 '22 02:11

Joey