为什么 width: 100% 不假设完整的 window 宽度大小?

Why width: 100% is not assuming the full window width size?

我有 HTML 代码和 CSS 下面:

body{
 background-color: #C7C7C7;
}
#content{
 background-color: #FFF;
 text-align: center;
}
.warp{
 padding:15px;
 display: inline-block;
 width: 700px;
 background-color: red;
}
#header{
 width: 100%;
 background-color: #000;
 color: #FFF;
}
<body>
<div id="header">
 HEADER IS HERE
</div>
<div id="content">
 <div class="warp">
  CONTENT IS HERE
 </div>
</div>
</body>

但是当我调整浏览器大小时,header div 而不是 width: 100%

您可以在这张图片中看到:

如何解决?

非常感谢。

这是因为当你调整浏览器大小时有一个固定的宽度 div 即 .wrap div 到 700px 如果你调整浏览器大小时 window 宽度最大700px 但 100% 宽度应用于视口宽度。

因此,您可以将最大宽度应用于 .wrap div:

.warp{
    padding:15px;
    display: inline-block;
    width: 700px;
    max-width: 100%;
    box-sizing: border-box;/*for padding values*/
    background-color: red;
}

因此,在较小的 window .wrap div 中不会超出 100% 视口宽度,您的页眉将与之对应,在较大的 window .wrap div 不会超过你想要的700px。


这是演示:

body{
 background-color: #C7C7C7;
}
#content{
 background-color: #FFF;
 text-align: center;
}
.warp{
 padding:15px;
 display: inline-block;
 width: 700px;
    max-width: 100%;
    box-sizing: border-box;
 background-color: red;
}
#header{
 width: 100%;
 background-color: #000;
 color: #FFF;
}
<body>
<div id="header">
 HEADER IS HERE
</div>
<div id="content">
 <div class="warp">
  CONTENT IS HERE
 </div>
</div>
</body>

嘿,你的 header 没问题。 问题出在您的

.warp{
    padding:15px;
    display: inline-block;
    width: 700px;<-- because of fixed width content go outside the body tag
    background-color: red;
}

因为 .warp{} 这个 div 你给了 width: 700px 修正。所以你可以使用媒体屏幕并给出 .warp{} div width: 100%。或者给出 .warp{} div 宽度百分比(%)。