【问题标题】:CSS: top percentage doesn't work on all browsersCSS:最高百分比不适用于所有浏览器
【发布时间】:2016-05-28 04:48:22
【问题描述】:

我的目标是将图像定位在 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%);
}

【问题讨论】:

  • 鉴于我已经花了一整天的时间解决这个问题,但没有成功,我会在符合条件的情况下奖励 50 分。

标签: css android-browser


【解决方案1】:

让您的父母 .containerrelative 和您的孩子 .container imgabsolute

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

来自MDN

绝对定位

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

片段

.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>

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2011-06-20
      • 2017-10-06
      • 2014-11-20
      • 1970-01-01
      • 2011-08-04
      • 2015-02-12
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      相关资源
      最近更新 更多