30

Can you help me to understand why my svg refuse to resize the height for helping me to center vertically in a div container ?

How can I process for align vertical svg in a container ? I seem to svg behaviour is not standard like div...

The main idea is that center horizontally AND vertically svg into a div.

I try this : https://jsfiddle.net/gbz7rp7u/1/#&togetherjs=0n9iL62pHv

<div id="svg-container">
  <svg id="svg-1" height="50%" width="50%" viewBox="0 0 1000 1000" xmlns="http://www.w3.org/2000/svg" version="1.1">
     <circle r="15" cx="350" cy="80"></circle>
  </svg>
</div>

#svg-container
{
  background-color: red;
}

#svg-1
{
  margin: auto auto;
  display: block;
  height: 30%;
}
darkomen
  • 4,281
  • 9
  • 35
  • 65

2 Answers2

75

html, body {
   height: 100%;  
}
#svg-container
{
  display: flex;
  align-items: center;
  background-color: red;
  height: 100%;
}

#svg-1
{
  margin: 0 auto;
  display: block;
}
<div id="svg-container">
  <svg id="svg-1" height="15px" width="15px" viewBox="0 0 30 30" xmlns="http://www.w3.org/2000/svg" version="1.1">
     <circle r="15" cx="15" cy="15"></circle>
  </svg>
</div>
Mehrad
  • 1,372
  • 15
  • 20
  • This code works, but why does setting `display: block` make the SVG vertically aligned? – bytrangle Jun 07 '21 at 14:05
  • 1
    `display: block` + setting the margin left+right to `auto` horizontally aligns it, its the `align-items: center;` that does the vertical – Mehrad Jun 07 '21 at 16:59
  • you could alternatively remove all the styles for `#svg-1` and add `justify-centent: center` to `#svg-container` to get the same result – Mehrad Jun 07 '21 at 17:02
  • 2
    Adding a `justify-content: center` on the container works too. Then no need to style the svg direcly ` #svg-container { display: flex; align-items: center; justify-content: cente background-color: red; height: 100%; } ` – mmnoo Aug 24 '21 at 22:10
11

html, body {
   height: 100%;  
}

#svg-container {
  background-color: red;
  height: 100%;
}

#svg-1 {
  display: block;
  margin: auto;
  height: 100%;
}
<div id="svg-container">
  <svg id="svg-1" height="15px" width="15px" viewBox="0 0 30 30" xmlns="http://www.w3.org/2000/svg" version="1.1">
     <circle r="15" cx="15" cy="15"></circle>
  </svg>
</div>
Anton Novik
  • 1,659
  • 1
  • 18
  • 31