Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does SVG with width = 0 and height = 0 take layout space?

Tags:

html

css

svg

Could you explain why does the first SVG in the following example take layout space even though it has width="0" and height="0"?

Is it possible to style it in a way that won't affect the layout?

body {
  display: flex;
}

.container {
  background-color: #ddd;
  margin-left: 30px
}

#blue {
  border: 1px solid blue;
}

#red {
  border: 1px solid red;
  display: block;
}
<div class="container">
  <svg id="blue" width="0" height="0"></svg>
  <svg id="red" width="100" height="100"></svg>
</div>
<div class="container">
  <svg id="red" width="100" height="100"></svg>
</div>
like image 648
Misha Moroshko Avatar asked Oct 18 '25 03:10

Misha Moroshko


2 Answers

The #blue has not defined the display property, so it defaults to inline, which according MDN says: "inline | The element generates one or more inline element boxes."

If you set the display to something like block, you will see that it takes up no additional space:

body {
  display: flex;
}

.container {
  background-color: #ddd;
  margin-left: 30px
}

#blue {
  border: 1px solid blue;
  display: block;
}

#red {
  border: 1px solid red;
  display: block;
}
<div class="container">
  <svg id="blue" width="0" height="0"></svg>
  <svg id="red" width="100" height="100"></svg>
</div>
<div class="container">
  <svg id="red" width="100" height="100"></svg>
</div>

Of course, if you want to hide it, display: none is the way to go.

like image 172
Automatico Avatar answered Oct 19 '25 18:10

Automatico


Use display: none; property to not display the element. Also do not use same ID for two elements(You have used ID "red" for 2 SVGs).

body {
  display: flex;
}

.container {
  background-color: #ddd;
  margin-left: 30px
}

#blue {
  border: 1px solid blue;
  display: none;
}

.red {
  border: 1px solid red;
  display: block;
}
<div class="container">
  <svg id="blue" width="0" height="0"></svg>
  <svg class="red" width="100" height="100"></svg>
</div>
<div class="container">
  <svg class="red" width="100" height="100"></svg>
</div>

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!