13

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?

basarat
  • 261,912
  • 58
  • 460
  • 511

1 Answers1

14

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.

Joey
  • 344,408
  • 85
  • 689
  • 683
  • I want `display: inline-block` on the svg since don't want it to line break – basarat Sep 27 '16 at 05:14
  • You're nesting an SVG inside a div. It's not going to break text any worse than the div already does (which is a block). But, as noted, you have two options. Heck, you can even fit the div's width by setting it to `display: table-cell`. – Joey Sep 27 '16 at 05:16
  • In my use case its `div > (svg+text)` So I need the svg to not be `display: block` – basarat Sep 27 '16 at 05:19
  • Would be helpful to include that factoid in your question, don't you think? *Still*, you *can* also set `line-height` on the div, as mentioned. – Joey Sep 27 '16 at 05:20
  • `display: block` fixed the problem thanks! – masterxilo Dec 03 '19 at 09:58