Reputation: 461
.center {
position: absolute;
left: 50%;
top: 50%;
/*
Nope =(
margin-left: -25%;
margin-top: -25%;
*/
/*
Yep!
*/
transform: translate(-50%, -50%);
/*
Not even necessary really.
e.g. Height could be left out!
*/
width: 40%;
height: 50%;
}
This works fine in the web browser. However on mobile tranforsm doesn't seem to be supported. What's a simple solution that works?
My HTML:
<div id="responsive-with-backgroundimg">
<img src="" class="center">
</div>
Upvotes: 0
Views: 2254
Reputation: 1550
Try:
.center {
position: absolute;
left: 0;
right:0;
top: 0;
bottom:0;
margin: auto;
width: 40%;
height: 50%;
}
You might as well should consider using flex
Upvotes: 0
Reputation: 587
at the moment this is my favorite way to center an image:
img.center {
position: absolute;
left: -9999px;
top: -9999px;
right: -9999px;
bottom: -9999px;
margin: auto;
}
Upvotes: -1
Reputation: 1042
In different browsers you have to work with prefixing your css this should look like this:
-webkit-transform: translate(-50%, -50%); /* Chrome, Opera 15+, Safari 3.1+ */
-ms-transform: translate(-50%, -50%); /* IE 9 */
transform: translate(-50%, -50%); /* Firefox 16+, IE 10+, Opera */
Upvotes: 0
Reputation: 22998
.center {
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
width: 40%;
height: 50%;
}
Upvotes: 2