Cuva Cuva - 1 year ago 113
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="" xmlns: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"/>

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.


Answer Source

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;
    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)                                                                                                            = = heightDiff / 2;
if (widthDiff > 0) = = widthDiff / 2;