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

时间:2016-02-16 18:36:06

标签: css css3 android-browser

我的目标是将图像放在div中间。它工作得很好,但出于某种原因,top对Android浏览器没有任何影响。

很可能,我的div设置不正确,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%);
}

2 个答案:

答案 0 :(得分:2)

将您的父级.container设为relative,将您的孩子.container img设为absolute

这是在Android 5.1.1中使用Firefox测试的。

来自 MDN

  

绝对定位

     

相对定位的元素仍然被认为是在   文档中元素的正常流动。相反,一个元素   绝对定位的是从流程中取出并因此占用   放置其他元素时没有空间。绝对定位   元素相对于最近定位的祖先定位(非   静态的)。如果定位的祖先不存在,则为初始容器   使用

&#13;
&#13;
.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%);
}
&#13;
<div class="container">
  <img src="http://i.imgur.com/qRkEJni.jpg">
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以使用此trick

&#13;
&#13;
.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;
}
&#13;
<div class="parentbox">
    <div class="childbox">
        I shall be in the middle of parentbox regardless of its size!
    </div>
</div>
&#13;
&#13;
&#13;