Search code examples
htmlcsswidth

How to extend section width: 100% using css


I have a section inside width: 1180px; i want to extend this green color div I want to make width: 100% I have tried using vw but not getting but some extra space is coming. can anyone suggest me? Is there any other way to do using 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>


Solution

  • You could use negative margin - the only problem with this approach is that if the page gets a vertical scroll, this will add a horizontal scroll as 100vw doesn't take into account the 20px caused by the vertical scroll:

    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>

    As I say in my comments, it would be better to just move the green div outside your wrapper