DrXCheng DrXCheng - 3 months ago 13
CSS Question

Fill two dynamic divs inside one

I have two divs inside one parent div.
I want the right div always stick to right and expand to the left if content inside is longer;
I want the left div to fill the remain part (content inside will be hidden)

I have done the research, but in all the similar questions, one div has a fixed width, whereas in my case, both are dynamic (one based on content, the other one based on the other div).

I can use javascript to dynamically change the width of left div, but is there a pure CSS way to achieve that?

Update: We need to support old browser so I can't use flexbox.

Answer

One way I can think of is using display: table-cell on the child divs. Note that even though the right div doesn't have a fixed width, its content must, so the right div can expand and the left div can take the remaining space.

.parent {
  width: 500px;
  margin-bottom: 10px;
}
.child {
  display: table-cell;
  width: 100%;
  height: 100px;
}
.left {
  background-color: rgba(255,0,0,.1);
}
.right {
  background-color: rgba(0,255,0,.1);
}

.parent:nth-child(2) .child.right p {
  width: 200px;
}
.parent:nth-child(3) .child.right p {
  width: 350px;
}
<div class="parent">
  <div class="child left">
    a
  </div>
  <div class="child right">
    b
  </div>
</div>

<div class="parent">
  <div class="child left">
    a
  </div>
  <div class="child right">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p> 
  </div>
</div>

<div class="parent">
  <div class="child left">
    a
  </div>
  <div class="child right">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>  
  </div>
</div>

<div class="parent">
  <div class="child left">
    right div content doesn't have a width
  </div>
  <div class="child right">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>  
  </div>
</div>