Search code examples
htmlcss

How to Make Full-Width Items in a Container with Padding in CSS?


I'm trying to create a layout where blue and white rectangles take the full width of the screen while keeping a padding inside the container. Here is my HTML and CSS code:

The problem is that the .item elements are not taking the full width of the container because of the padding. How can I make these items take the full width of the screen while keeping the container's padding?

html, body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}

.container {
  background-color: red;
  width: 100%;
  height: 100%;
  padding: 0 20px;
}

.item {
  width: 100%;
  height: 20%;
}

.item:nth-child(odd) {
  background-color: blue;
}

.item:nth-child(even) {
  background-color: white;
}
<div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>


Solution

  • Here's one way you can do it:

    * {box-sizing: border-box;}
    
    html, body {
      margin: 0;
      padding: 0;
      width: 100%;
      height: 100%;
    }
    
    .container {
      background-color: red;
      width: 100%;
      height: 100%;
      padding: 0 20px;
    }
    
    .item {
      width: 100%;
      height: 20%;
      clip-path: inset(0 -100vmax);
    }
    
    .item:nth-child(odd) {
      background-color: blue;
      box-shadow: 0 0 0 100vmax blue;
    }
    
    .item:nth-child(even) {
      background-color: white;
      box-shadow: 0 0 0 100vmax white;
    }
    <div class="container">
      <div class="item"></div>
      <div class="item"></div>
      <div class="item"></div>
      <div class="item"></div>
      <div class="item"></div>
    </div>