Grow a div in priority before its sibling

47 Views Asked by At

I have a page that can have two styles depending on users settings:

Style 1:

div > div {
    writing-mode: vertical-rl;
    text-orientation: upright;
}

.left {
  background-color: lightgreen;
  float: left;
}

.right {
  background-color: red;
  float: right;
}

.end {
  background-color: lightblue;
  float: left;
}

.left,
.right,
.end {
  width: 50%;
}
<div>
  <div class="left">LEFT</div>
  <div class="right">RIGHT</div>
  <div class="end">END</div>
</div>

Style 2:

div > div {
    writing-mode: vertical-rl;
    text-orientation: upright;
}

.left {
  background-color: lightgreen;
  float: left;
}

.right {
  background-color: red;
  float: right;
}

.end {
  background-color: lightblue;
  float: left;
}

.left,
.right {
  width: 50%;
}

.end {
  width: 100%;
}
<div>
  <div class="left">LEFT</div>
  <div class="right">RIGHT</div>
  <div class="end">END</div>
</div>

This works fine, yet it's not as versatile as I wish. For example, I'd like .left and .right to have dynamic width instead of fix width:

.left,
.right {
  min-width: 40%;
  max-width: 60%;
}

and make .left grow in priority, i.e.:

  • .left width is at least 40%
  • if .left content is larger than 40%, .left can grow to take as much as 60%
  • .right width is at least 40%
  • if .right content is larger than 40%, it can grow to take as much remaining space as possible (so if .left is already taking 60% it cannot grow at all).

Finally, each div height is dynamic and grow according to the div content.

It does not seem to be possible to achieve with CSS float (as divs are not aware of each other width), but would it be possible to achieve with CSS Grid ?

1

There are 1 best solutions below

2
soheil izadi On

Just slap this into your stylesheet, and you've got a layout that adapts dynamically, giving .left the attention it deserves while keeping everything in harmony.

.container {
  display: grid;
  grid-template-columns: minmax(40%, 60%) auto;
  writing-mode: vertical-rl;
  text-orientation: upright;
}

.left {
  background-color: lightgreen;
  grid-column: 1;
}

.right {
  background-color: red;
  grid-column: 2;
}

.end {
  background-color: lightblue;
  grid-column: 1 / span 2;
}
<div class="container">
  <div class="left">LEFT</div>
  <div class="right">RIGHT</div>
  <div class="end">END</div>
</div>