Vertically center SVG Tag

Cuva picture Cuva · Jan 14, 2013 · Viewed 37.4k times · Source

I'm trying to figure out a way to center vertically my SVG Tag.

Basically, here is a simplified SVG code i'm trying to center :

<svg height="272" style="background-color:transparent;margin-left: auto; margin-right: auto;" width="130" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <g style="font-size: 0.7em;" transform="scale(1 1) rotate(0) translate(0 270)">
        <g id="1" style="font-size: 0.7em;">
            <image height="32" width="32" x="49" xlink:href="../../images/JOB.GIF" y="-270"/>
        </g>
    </g>
</svg> 

I have no trouble putting it in the middle (horizontally speaking) of the page, however i'd like it to be vertically centered as well.

I can add wrappers, but i'd like to know a generic way of doing this, not depending on the SVG size nor the window size.

I have tried multiple ways, but nothing worked.

Thanks,

Answer

Maciej Paprocki picture Maciej Paprocki · Jan 14, 2013

I updated this answer as current browser have a lot better solution for that.

How wise man said, first year you learn html and css, for another few years you learn advanced javascript and after five years you finally learn how to vertically center div.

to vertically/horizontally align anything in css you can use two main ways:

Absolute

<div class="outside">
    <div class="inside">Whatever</div>
</div>

and css:

.outside{
    position:relative;
}
.inside{
    position:absolute;
    top:50%;
    bottom:50%;
    transform:translate(-50%, -50%);
}

the only issue with that is that element doesn't generate the height.

Flexbox

Flexbox has now pretty good support so why not to use it. https://caniuse.com/#feat=flexbox

Using flexbox your item doesn't need to be absolute so it will generate the height. code:

<div class="outside">
    <div>Whatever</div>
</div>

and css:

.outside{
    display: flex;
    align-items: center;
    justify-content: center;
}

Old answer:

you have height and width so u can use margin : auto auto;

or put it in div with

position:absolute ;
left:50% ;
margin-left: -(half of width of image)px;
top:50% ;
margin-top: -(half of height of image)px;

the second one will be better if u will be doing some stuff with it (javascript animation or something)

I didn't check it but maybe u can use second option for svg (without outer div) too