【问题标题】:Inconsistent percentage margin calculation for absolutely positioned item绝对定位项目的百分比边距计算不一致
【发布时间】:2014-02-12 23:57:44
【问题描述】:

我有一种情况,我在一般容器中有一个“底部”内容 div。这个 div 应该保持在底部(具有绝对定位),但与容器底部有一个百分比间隙。百分比应该是相对于容器的宽度。

我们不能使用 'bottom:5%' 因为as the position props define 这是相对于高度的。保证金呢?是的!它适用于 Chrome .. 和 Firefox。啊,但不是在 Safari 中。 Chrome 和 Safari 似乎是根据容器宽度和 Safari 根据容器高度来计算的。

在 Chrome 和 Safari 中查看 this fiddle,您会看到不一致之处。 CSS 样式:

.container {
    background: #990000;
    width: 345px;
    height: 200px;
    position: relative;
}
.bottom {
    background: #000;
    width: 100%;
    height: 40px;
    position: absolute;
    bottom: 0;
    margin-bottom: 5%;
}

任何人都知道错误在哪里 - 与 Safari?铬/火狐?规格?

快速检查显示填充可能始终如一地工作,但对于想要使用边距的人来说并不理想(即当背景发挥作用时)。

【问题讨论】:

  • 我在 Windows7 上的 Safari/Chrome/Firefox 中没有发现问题
  • Mac:10.8.2,Chrome:27.0.1453.93,Safari:6.0.2 (8536.26.17)

标签: css margin css-position safari


【解决方案1】:

问题在于 Safari。 W3C 标准规定,使用百分比定义的边距应该相对于包含块的宽度(而不是高度)计算。

查看:http://www.w3.org/TR/2011/REC-CSS2-20110607/box.html#margin-properties

所以基本上,你被这个错误困住了。但是,我建议使用一些 JS 来定位 Safari,获取容器的宽度并应用该宽度的百分比作为边距。

例如:

    var width = $('.container').width();    // get the width of div.container
    var bottomMargin = width * 0.05;       // multiply the width by 0.05 to get 5% of the container width

    // look to see if the browser is Safari
    if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {                  
        $('.bottom').css('margin-bottom', bottomMargin+'px');   // apply our margin to div.bottom
    }
    else {
    };;

我在 JS Fiddle 中实现它时遇到了一些麻烦,所以创建了一个页面 here

希望有帮助!

【讨论】:

    【解决方案2】:

    我在使用 Android 浏览器时遇到了同样的问题,并且能够通过将边距放在子元素上来解决它。

    .bottom {
        position: absolute;
        bottom: 0;
        width: 100%;
        height: 40px;
    }
    .bottom-child {
        height:100%;
        margin-bottom: 5%;
        background: #000;
    }
    

    关键是不要把margin放在绝对定位的元素上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      • 2011-04-07
      • 2012-12-26
      • 2020-11-26
      • 2013-01-23
      • 1970-01-01
      相关资源
      最近更新 更多