MasterNone
MasterNone

Reputation: 568

Stretching a div in inside a max-width div to viewport fullwidth responsively?

Is it possible to stretch it and making it work when you decrease or increase the window width? Without changing anything else besides the div.wide or inside ones.

Can it be done in CSS math somehow or only JS?

https://codepen.io/rKaiser/pen/GwGNpy

.wide {
  background:green;
  height:200px;
  /**/
  margin-left:-20%;
  margin-right:-20%;
}

Upvotes: 2

Views: 491

Answers (1)

random_user_name
random_user_name

Reputation: 26180

Certainly!

Meet your new friendly CSS unit, vw and vh!

Minimally, your code would change like so:

.wide {
  background:green;
  height:200px;
  // use calc to sort out the left margin to break out of the inner container
  margin-left:calc((100vw - 800px) / -2);
  // set width to full viewport width
  width: 100vw;
}

Here's your CodePen, modified to show the result: https://codepen.io/anon/pen/KreNGK

A few notes:

  1. If you have padding or border on the .wide element, you may want to set box-size: border-box; so the width is still correct. (more on box-size)
  2. You'll probably want to set up some media queries for scenarios where the viewport with is less than the 800px inner element.
  3. The calc above could be simplified to calc(-50vw + 400px);, however the structure I used is based on the idea of using variables (such as with SCSS or LESS), so it could end up being calc((100vw - $inner-width) / -2); and still work properly...

Upvotes: 4

Related Questions