html - 百分比填充未正确添加总高度

标签 html css

所以我有一个包含 htmlheaderbodydiv 标签等的页面。对于 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/

相关文章:

html - 是否可以仅使用 CSS 隐藏悬停图像并显示另一幅图像?

html - 使用 CSS 边距和填充溢出页面容器的背景颜色

javascript - 在 PHP 中创建 onchange/oninput 监听器

HTML + CSS 标签栏

jquery - 图像无响应或无法调整为最大宽度值

javascript - 如何从切换开关 JavaScript 获取输入

html - 为什么图像在 MAC 上不占据浏览器的整个宽度?

html - 如何正确地将表格置于其 div 容器中?

javascript - 将图像与窗口的底部边缘对齐

html - 当它是编码的 CSS 背景图像时如何更改 SVG 颜色?