我有一种情况,我在一般容器中有一个'底部'内容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%;
}
任何人都知道这里的bug在哪里 - 使用Safari?镀铬/火狐?规范?
快速检查表明填充可能会一致地工作,但对于那些想要使用保证金的人来说(即当背景进场时),它并不理想。
答案 0 :(得分:2)
问题在于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 。
希望有所帮助!
答案 1 :(得分:0)
Android浏览器遇到了同样的问题,并且可以通过将边距放在子元素上来解决它。
.bottom {
position: absolute;
bottom: 0;
width: 100%;
height: 40px;
}
.bottom-child {
height:100%;
margin-bottom: 5%;
background: #000;
}
关键是不要将边距放在绝对定位的元素上。