CSS:最高百分比不适用于所有浏览器

CSS: top percentage doesn't work on all browsers

我的目标是将图像放在 div 的中间。它运行良好,但由于某些原因,top 对 Android 浏览器没有任何影响。

很有可能,我的 divs 设置不正确,其中 img 无法确定它的容器高度(因此百分比没有意义...)。

这里是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%);
}

将你的 parent .container 设为 relative 并将你的 child .container img 设为 absolute

这已在 Android 5.1.1 中使用 Firefox 进行了测试。

来自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>

你可以使用这个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>