I'm aiming to position an image to the middle inside a div. It works great, but for some reason, top
doesn't have any effect on the Android browser.
Very likely, I have my divs set incorrectly where the img one cannot determine it's container height (so percentage makes no sense...).
Here is a jsfiddle.
HTML:
<div class="container">
<img src="http://i.imgur.com/qRkEJni.jpg">
</div>
CSS:
.container {
height:200px;
width:200px;
float:left;
overflow: hidden;
}
.container img {
height: auto;
width:100%;
top:50%;
left:0;
position: relative;
-webkit-transform: translate(0,-50%);
-moz-transform: translate(0,-50%);
-ms-transform: translate(0,-50%);
-o-transform: translate(0,-50%);
transform: translate(0,-50%);
}
Make your parent .container
as relative
and your child .container img
as absolute
This was tested in Android 5.1.1 using Firefox.
From MDN
Absolute positioning
Elements that are positioned relatively are still considered to be in the normal flow of elements in the document. In contrast, an element that is positioned absolutely is taken out of the flow and thus takes up no space when placing other elements. The absolutely positioned element is positioned relative to nearest positioned ancestor(non static). If a positioned ancestor doesn't exist, the initial container is used
.container {
height: 200px;
width: 200px;
float: left;
overflow: hidden;
position:relative;
}
.container img {
height: auto;
width: 100%;
top: 50%;
left: 0;
position:absolute;
-webkit-transform: translate(0, -50%);
-moz-transform: translate(0, -50%);
-ms-transform: translate(0, -50%);
-o-transform: translate(0, -50%);
transform: translate(0, -50%);
}
<div class="container">
<img src="http://i.imgur.com/qRkEJni.jpg">
</div>