Home > Software design >  Stretch divs based on wrapper AND on window positions without JS
Stretch divs based on wrapper AND on window positions without JS

Time:08-20

The following image will be helpful.

Consider a traditional centered wrapper with max-width.

Then wrapper has 2 columns using 40% and 60% of the wrapper respectively (random number that isn't 50%).

Is there a way to stretch the divs outter limit to match the window borders without Javascript - while the inner limits respect the wrapper reference?

divs stratching

This unfortunatelly doesn't work:

#div1{
    left: 0vw;
    right: 40%; /*of .wrapper */
}

#div2{
    left: 40%; /*of .wrapper */
    right: 100vw;
}

Solution with JS (poorly written): https://jsfiddle.net/sirojuntle/ktvap86c/12/

The idea is to make smaller desktop layout looks better in larger screens.

Thanks

CodePudding user response:

Because your wrapper is position: relative; half your job is already done. Even with position: absolute; your divs still take the wrapper as their parent co-ordinates.

With that in mind, it's easier than you think.

.div1{
right: 60%; /* is 40% from the left, like your picture */
left: calc(50% - 50vw)
}
.div2{
left: 40%;
right: calc(50% - 50vw)
}

CodePudding user response:

You can play with negative margin

.wrapper {
  --m: min(0px, (800px - 100vw)/2);
}
.row1 {
  width: calc(40% - var(--m));
  margin-left: var(--m);
}
.row2 {
  width: calc(60% - var(--m));
  margin-right: var(--m);
  margin-left:auto;
}

Full code:

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  padding: 0;
}

.wrapper {
  --m: min(0px, (800px - 100vw)/2);
  
  border: 3px solid pink;
  max-width: 800px;
  background-size: 10%;
  background-image: linear-gradient(90deg, #000, #0000 5%);
  margin:auto;
}

.row1 {
  background-color: red;
  min-height: 100px;
  width: calc(40% - var(--m));
  margin-top: 20px;
  margin-bottom: 20px;
  margin-left: var(--m);
}

.row2 {
  background-color: darkred;
  width: calc(60% - var(--m));
  margin-left:auto;
  margin-right: var(--m);
  min-height: 100px;
}
<div  id="wrapper">
    <div  id="ref">
      There is a way to stretch this with CSS?
    </div>
    <div  id="ref2">
      And that?
    </div>
  </div>

  • Related