Skip to content
Advertisement

Possible to have 100% screen width inside limited div with relative position?

I wonder if it’s possible to have a div stretch to 100vw, while being inside a relative parent div with limited width. And in the process also not losing it’s height inside the document, as it would when setting position to absolute.

Is it possible with pure css? Or do I need some jQuery / JS?

body {
  background: #f0f0f0;
  text-align: center;
}

.parent {
  max-width: 300px;
  height: 300px;
  margin: auto;
  position: relative;
  background: white;
}

p {
  padding: 20px;
}

#banner {
  padding: 20px;
  background: black;
  color: white;
}
<div class="parent">
  <p>My relative parent container,<br>with a fixed width.</p>
  <div id="banner">
    My full width banner
  </div>
  <p>...</p>
</div>

Anyone has any experience in getting this to work? Any and all tips are much appreciated. Thanks!

Advertisement

Answer

Yes, you can use 100vw width. To correct the position, you can add margin-left: calc(-50vw + 50%);, which moves it half of the screen width to the left and then back 50% of its own width to the right, thereby “centering” it again, which in this case results in a full-width element:

body {
  background: #f0f0f0;
  text-align: center;
}

.parent {
  max-width: 300px;
  height: 300px;
  margin: auto;
  position: relative;
  background: white;
}

p {
  padding: 20px;
}

#banner {
  padding: 20px;
  background: black;
  color: white;
  width: 100vw;
  margin-left: calc(-50vw + 50%);
}
<div class="parent">
  <p>My relative parent container,<br>with a fixed width.</p>
  <div id="banner">
    My full width banner
  </div>
  <p>...</p>
</div>

There is one problem remaining however: As soon as the contents are longer than the window height, a horizontal scrollbar will appear. I previously brought up that problem in this question, but I haven’t really found a solution or got a satisfying answer for it.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement