当我开始使用百分比填充时,我无法将我的 div 与 box-sizing:border-box 对齐,框的位置将与位置的百分比不匹配。
这是代码,将它粘贴到任何 html 文件中以查看它:
<!DOCTYPE html>
<html>
<head>
<title>Testing</title>
<style type="text/css" media="screen">
body{
width:100%;
height:100%;
background-color: blue;
overflow:none;
padding:0;
margin:0;
}
#box{
padding-top:50%;
width:100%;
height:100%;
background-color:blue;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#light{
width:100%;
background-color:yellow;
}
</style>
</head>
<body>
<div id='box'>
<div id='light'>
halo world
</div>
</div>
</body>
</html>
黄色的 div 将位于底部附近,而我将填充百分比设置为 50%。这是一个错误还是我错误地理解了边界框的概念,它将填充与宽度和高度一起附加。
在 chrome 和 firefox 上测试。
编辑
由@Claude Grecea 建议尝试使用更简单的方法,没有主体高度,并按像素固定 div 高度。但是,如果我把 padding-top:50%.
<!DOCTYPE html>
<html>
<head>
<title>Testing</title>
<style type="text/css" media="screen">
.box{
height:1000px;
padding-top:50%;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
background-color:#C1C1C1;
}
</style>
</head>
<body>
<div class="box">
halo world
</div>
</body>
</html>
最佳答案
我相信这是因为你 body 的 100% 高度会占据屏幕尺寸。此外,如果您想使 div 居中,则使用边距,即使在 100% 时也能为您提供所需的外观;
CSS 中的“盒子模型”是这样工作的:
width + padding + border = 框的实际可见/渲染宽度 height + padding + border = 框的实际可见/渲染高度
关于css - 使用按百分比填充的边界框大小定位问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12506980/