40

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%;
}
miltone
  • 4,416
  • 11
  • 42
  • 76

2 Answers2

88

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>

Another way to center anything inside the container is using grid like this:

#svg-container {
  display: grid;
  place-items: center;
}
Mehrad
  • 1,495
  • 14
  • 22
  • 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
  • 3
    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
12

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,768
  • 1
  • 19
  • 31
  • This works, but precludes me from putting anything under the svg (as the SVG takes the full height of the screen) – Michael Mar 05 '23 at 17:20