所以我有一个包含 html
、header
、body
、div
标签等的页面。对于 CSS ,我有:
* {
margin: 0;
padding: 0;
}
html {
width: 100%;
height: 100%;
}
body {
width: 98%;
height: 98%;
padding: 1%;
}
我的问题是浏览器右侧有一个滚动条。意思是高度太高了?
html
设置为 100%
高度和宽度。 body
有一个 1%
填充,它在顶部、右侧、底部和左侧添加了 1%
,所以这是 width - 2 = 98
和 height - 2 = 98
。
所以填充 1%
高度 98%
,宽度 98%
。我如何获得滚动条?
最佳答案
它没有按预期工作,因为基于百分比的 padding
是相对于元素的宽度的。如果您调整浏览器的大小,使高度大于宽度,您会注意到滚动条消失了(这是因为 padding
是相对于宽度的)。
根据规范:
8 Box model - 8.4 Padding properties:
The percentage is calculated with respect to the width of the generated box's containing block, even for 'padding-top' and 'padding-bottom'. If the containing block's width depends on this element, then the resulting layout is undefined in CSS 2.1.
一种可能的解决方法是使用视口(viewport)百分比单位,例如 vw
以使百分比相对于宽度:
body {
width: 98%;
height: 98%;
padding: 1vh 1vw;
}
您还可以添加 box-sizing: border-box
在元素的尺寸中包含 padding
:
body {
width: 100%;
height: 100%;
padding: 1%;
box-sizing: border-box;
}
关于html - 百分比填充未正确添加总高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34446638/