如何扩展部分宽度:100% 使用 css

How to extend section width: 100% using css

我在里面有一个部分 width: 1180px; 我想扩展这个绿色 div 我想使宽度:100% 我试过使用 vw 但没有得到,但有一些额外的space 来了。谁能建议我?还有其他方法可以使用 CSS.

.wrapper {
  width: 100%;
  position: relative;
  background: #ccc;
}

.inner {
  width: 1180px;
  margin: 0 auto;
  background: pink;
}

.box1 {
  height: 50px;
  background: red;
}

.box2 {
  height: 50px;
  background: green;
  margin-left: calc(-100vw/2 + 100%/2);
  margin-right: calc(-100vw/2 + 100%/2);
  width: 100vw;
}
<div class="wrapper">
  <div class="inner">
    <div class="box1"></div>
    <div class="box2"></div>

  </div>
</div>

.wrapper {
  width: 100%;
  position: relative;
  background: #ccc;
}

.inner {
  width: 1180px;
  margin: 0 auto;
}

.box1 {
  height: 50px;
  background: red;
}

.box2 {
  height: 50px;
  background: green;
}
<div class="wrapper">
  <div class="inner">
    <div class="box1"></div>
    <div class="box2"></div>

  </div>
</div>

您可以使用负边距 - 这种方法的唯一问题是如果页面获得垂直滚动,这将添加水平滚动,因为 100vw 没有考虑垂直滚动引起的 20px:

body {
  margin: 0;
}

.wrapper {
  width: 100%;
  position: relative;
  background: #ccc;
}

.inner {
  width: 1180px;
  margin: 0 auto;
  background: pink;
}

.box1 {
  height: 50px;
  background: red;
}

.box2 {
  height: 50px;
  background: green;
  width: 100%;
}

@media screen and (min-width:1180px) {
  .box2 {
    margin: 0 calc(((100vw - 1180px) / 2) * -1);
    width: auto;
  }
}
<div class="wrapper">
  <div class="inner">
    <div class="box1"></div>
    <div class="box2"></div>
  </div>
</div>

正如我在评论中所说,最好将绿色 div 移到包装外

您需要使用媒体查询重置边距。最初你有一个负边距,但在 1180px 之后它将是一个正边距,创建不需要的 space。您也不需要使用 vw 单位设置 width。保持默认宽度就够了:

.wrapper {
  width: 100%;
  position: relative;
  background: #ccc;
}

.inner {
  width: 1180px;
  margin: 0 auto;
  background: pink;
}

.box1 {
  height: 50px;
  background: red;
}

.box2 {
  height: 50px;
  background: green;
  margin-left: calc(-100vw/2 + 100%/2);
  margin-right: calc(-100vw/2 + 100%/2);
}
@media all and (max-width:1180px) {
  .box2 { 
    margin:0;
  }
}
<div class="wrapper">
  <div class="inner">
    <div class="box1"></div>
    <div class="box2"></div>

  </div>
</div>

试试这个:

.wrapper {
  width: 100%;
  position: relative;
  background: #ccc;
}

.inner {
  width: 1180px;
  margin: 0 auto;
  background: pink;
}

.box1 {
  height: 50px;
  background: red;
}

.box2 {
  height: 50px;
  background: green;
  width: 100%;
}
<div class="wrapper">
  <div class="inner">
    <div class="box1"></div>
    <div class="box2"></div>

  </div>
</div>