CSS 宽度 100% 限于浏览器 window(它不会扩展到右侧滚动区域)

CSS width 100% limited to browser window (it doesn't extend to right scrolling area)

此站点 full-width 并适应浏览器的大小 window。但是,一旦浏览器 window 小于显示的内容,一旦向右滚动,标题就会被截断。

100% 的默认宽度似乎仅适用于浏览器的宽度 window,不适用于页面的宽度!同样的道理似乎也适用于纵轴。


例子

#title
{
  height: 50px;
  color: white;
  background-color: #404040;
}
#content
{
  width: 800px;
  background-color: #f0f0f0;
}
<div id="title">
    TITLE
</div>
<div id="content">
    CONTENT
</div>


实际结果

这是页面向左滚动时的样子

(为了简单和隐私,与问题无关的内容被删除。)

很明显 width: 100% 占用了 window 的宽度,而不是文档的宽度。

据我所知,规范中的这种行为并不完全清楚。

10.2 Content width: the width property

<percentage>

Specifies a percentage width. The percentage is calculated with respect to the width of the generated box's containing block. If the containing block's width depends on this element's width, then the resulting layout is undefined in CSS 2.1.


解决该问题的两种方法涉及 CSS 定位。

1. position: fixed

固定定位使宽度相对于视口。

#title { 
  height: 50px;
  color: white;
  background-color: #404040;
  position: fixed; /* NEW */
  width: 100%; /* NEW */
}

DEMO

2。 position: absolute

绝对定位也有效:

#title {
  height: 50px;
  color: white;
  background-color: #404040;
  position: absolute;
  width: 100%; 
}

DEMO

在摆弄定位之后,我终于想出了一些办法。

body
{
    position: absolute;
    min-width: 100%;
    min-height: 100%;
}

#menu-background
{
    z-index: -1;
    position: absolute;
    width: 250px;
    height: 100%;
    background-color: #404040;
}

和菜单背景HTML

<div id="menu-background"></div>

<body>需要绝对定位,否则内容div的table会溢出内容div。此外,它需要 100% 的 min-width 来涵盖这两种情况:window 更小,或者更大。

菜单的工作方式相同,只是它是一个横跨整个页面的 <div>


此解决方案非常适合 X 和 Y(菜单和标题)拉伸和背景颜色。

对我来说,它与这两个小朋友一起工作:

width: auto;
min-width: 100%;

不需要positon: fixed/absolute