css 中的百分比单位与窗口大小和/或分辨率的关系



为什么我必须将div的高度设置为88%而不是94%-(100%-(3%+ 3%(填充(,更重要的是,为什么当我使窗口变小时会出现主体(由其背景颜色指示(?我有两个不同分辨率的屏幕,它们在两个屏幕上的行为相同。我希望空间充满div但没有垂直滚动条,窗口的大小应该无关紧要......

html {
height: 100%;
}
body {
height: 100%;
margin: 0;
background-color: tomato;
}
<div style="padding: 3%; background-color: orange; height: 88%;">
</div>

padding: 3%意味着宽度的 3% 用于所有 4 个填充值 - 在大多数情况下,这将超过高度的 3% - 此div从一个屏幕到下一个屏幕的大小不正确。

一种解决方案可能是使用box-sizing: border-box

(将框大小设置为元素上的border-box意味着填充和边框包含在尺寸中,因此我们可以安全地将height: 100%与任何填充值一起使用(

html {
height: 100%;
}
body {
height: 100%;
margin: 0;
background-color: tomato;
}
<div style="padding: 3%; background-color: orange; height: 100%; box-sizing: border-box;">
</div>

背景属性设置为整个内部内容 填充分配给内部内容属性, 因此,您必须设置边距属性而不是填充:)

html {
height: 100%;
}
body {
position: fixed;
height: 100%;
width: 100%;
margin: 0;
background-color: tomato;
}
.container {
position: relative;
margin: 3%; 
background-color: orange; 
height: 88%;
}
<div class="container">
</div>

最新更新