3

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%);
}
j08691
  • 204,283
  • 31
  • 260
  • 272
Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155

2 Answers2

2

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

Snippet

.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>
dippas
  • 58,591
  • 15
  • 114
  • 126
1

You can use this trick

.parentbox {
    width:500px;
    height:400px;
    border-style:solid;
    
    text-align: center;  /* align the inline(-block) elements horizontally */
    font: 0/0 a;         /* remove the gap between inline(-block) elements */
}

.parentbox:before {      /* create a full-height inline block pseudo-element */
    content: ' ';
    display: inline-block;
    vertical-align: middle; /* vertical alignment of the inline element */
    height: 100%;
}

.childbox {
    display: inline-block;
    vertical-align: middle;          /* vertical alignment of the inline element */
    font: 16px/1 Arial, sans-serif;  /* reset the font property */
    
    padding: 5px;
    border: 2px solid black;
}
<div class="parentbox">
    <div class="childbox">
        I shall be in the middle of parentbox regardless of its size!
    </div>
</div>
solimanware
  • 2,952
  • 4
  • 20
  • 40