Cuva Cuva - 5 months ago 35
CSS Question

Vertically center SVG Tag

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

I've finally used some JS code to do so.

I was using the solution from here : Best way to center a <div> on a page vertically and horizontally?

Which is :

div {
    width: 100px;
    height: 100px;
    background-color: red;

    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;

}

But the problem is that if the SVG is bigger than the window size, it gets cropped. Here is the JS code i've used in onLoad :

var heightDiff = window.innerHeight - svg.height.baseVal.value;
var widthDiff = window.innerWidth - svg.width.baseVal.value;
if (heightDiff > 0)                                                                                                                
    svg.style.marginTop = svg.style.marginBottom = heightDiff / 2;
if (widthDiff > 0)
    svg.style.marginLeft = svg.style.marginRight = widthDiff / 2;