首页 > 解决方案 > 转义固定宽度的 CSS 列

问题描述

如果您被困在页面换行中 - 假设页面的所有内容都在一个宽度为 900 像素的 div 中,那么您需要一个 div 内,即整个页面宽度。最简单的方法是什么?

我知道你可以结束 900px div,做全宽 div,然后开始另一个 900px div,但是有没有办法设置内部 div 的样式,这样你就不必逃避它了?100vw 可以使其尺寸合适,但不能将其放置在正确的位置。

如此简单的例子:

<div style="width:900px;margin-right:auto;margin-left:auto;display:block;">
   <p>text text</p>
   <div style="width:100vw;">
      <p>I want this section to be the full page width and centered</p>
   </div>
   <p>text text</p>
</div>

谢谢!

标签: htmlcss

解决方案


您可以使用负左边距(-50vw + half parent width)

body {margin: 0;}
#a {background: red;}
#b {background: green; margin-left: calc(-50vw + 200px)
<div id="a" style="width:400px;margin-right:auto;margin-left:auto;display:block;">
   <p>text text</p>
   <div style="width:100vw;" id="b">
      <p>I want this section to be the full page width and centered</p>
   </div>
   <p>text text</p>
</div>

对于这个代码示例,我添加了IDs(用于更简洁的 CSS 样式)并将父 div 更改为400px(因为窗口较小)。


推荐阅读