1

i have div element with width: 100px and aspect-ratio: 1, but why when i add svg inside it, it's height become 104px?

this is the code:

<div class="container">
  <svg viewBox="0 0 100 100"></svg>
</div>

<style>
  .container {
    width: 100px;
    aspect-ratio: 1;
    background: red;
  }

  svg {
    background: blue;
  }
</style>
prs_wjy
  • 185
  • 1
  • 12

1 Answers1

3

By default, SVG elements are inline elements, meaning they have a default display value of inline and they sort of behave like text. As a result, inline SVG elements are subject to the styling effects of line-height, which in browsers typically defaults to normal or something slightly larger than 1. This means that in addition to the 100px of height provided by the SVG element, the line it's in will also add a little height.

There are a couple of approaches to fix this. First, you can set the line-height of your container to 0 in CSS:

.container {
  width: 100px;
  aspect-ratio: 1;
  background: red;
  line-height: 0;
}

Alternatively, you can set the display value of your SVG elements to some type of block, or vertical-align to top:

svg {
  display: block; /* or inline-block, or */
  vertical-align: top;
  background: blue;
}
Dennis Kats
  • 2,085
  • 1
  • 7
  • 16
  • wow, it works! i have been looking the answer for this behavior, but never solve it. how do you know this? is there any documentation for this? just want to know – prs_wjy Mar 16 '23 at 04:48
  • You could potentially extract this behavior from the [`line-height`](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height) and [box model](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/The_box_model) documentation, but personally, my knowledge mostly just comes from experience and randomly stumbling across it one day. – Dennis Kats Mar 16 '23 at 05:36