且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

CSS样式BODY标签问题

更新时间:2023-11-30 17:11:16


背景颜色只有一个屏幕高度下降然后结束,I
看起来不明白为什么!

the background colour only goes one screen height down then ends and I cant seem to figure out why!

这是原因:

body { 
    height:100%;
}

html { 
    height: 100%;
}

问自己:100%的什么?答案是不是 100%的内容。百分比高度始终指的是父元素元素的高度的百分比。由于您尚未设置任何显式高度(以像素为单位),因此浏览器使用视口的高度,并计算高度 body 为100%的。

Ask yourself: 100% of what? The answer is not 100% of the content. Percentage heights always refer to a percentage of the height of the parent element. Since you have not set any explicit heights (in pixels), the browser uses the height of the viewport and calculates the height body to be 100% of that.

视口是浏览器中的可见区域。由于您的内容延伸到此区域以下(即,您必须向下滚动以查看所有内容),所以它在 body 之外,因此在 body $ c>。

如果您未指定 html body ,它们只会与内容一样高,但 html 的背景将仍然填充

If you don't specify a height for html or body, they will only be as tall as the content, but the background for html will still fill the viewport.

所以解决方案是:

html {
    height:100%; 
    /* sets html to height of viewport 
      (bg color will still cover viewport) */
}
body {
    /* don't set explicit height */

    min-height:100%;
    /* expands body to height of html,
       but allows it to expand further
       if content is taller than viewport */
}

您不需要任何其他内容元素; body 的行为像任何其他元素。只有 html 有点不同,因为它的背景颜色将覆盖整个视口,即使计算的高度不同于视口或任何子元素。

You don't need any additional content elements; the body behaves like any other element. Only html is a bit different since its background-color will cover the whole viewport even if the calculated height is different from the viewport or any child elements.

您可能需要一些黑客来处理不了解最小高度的旧版浏览器。

You may need some hacks to handle older browsers that don't understand min-height.