Search code examples
csswidthoverflow

With CSS; how to style the non-overflowing element to span 100% of parent?


I'm trying to have the Non overflowing DIV to have the width of the parent.

.parent {
  width: 300px;
  height: 100px;
  background-color: lightblue;
  overflow: auto;
}

.parent .child-1 {
    width: 800px;
    background-color: lightgreen;
}

.parent .child-2 {
  background-color: lightyellow;
}
<div class="parent">
  <div class="child-1">Overflowing DIV</div>
  <div class="child-2">Non Overflowing DIV</div>
</div>

Thank you in advance :)


Solution

  • is this what you try to do ?

    .parent {
      width: 300px;
      height: 100px;
      background-color: lightblue;
      overflow: auto;
      display:grid; 
      grid-auto-rows:min-content;
    }
    
    .parent .child-1 {
        width: 800px;
        background-color: lightgreen;
    }
    
    .parent .child-2 {
      background-color: lightyellow; 
      
    }
    <div class="parent">
      <div class="child-1">Overflowing DIV</div>
      <div class="child-2">Non Overflowing DIV<!-- but does fit to the widest--></div>
    </div>

    get all children fit to the widest one ?

    Grid can be used to recalculate width avalaible on each rows. (no need of a grid-area or template here, it's a single column, only rows can be shrinked to their own height via grid-auto-rows.)


    As commented By Temani Afif , align-content: start does the job too to shrink rows to their content.

    .parent {
      width: 300px;
      height: 100px;
      background-color: lightblue;
      overflow: auto;
      display:grid; 
      align-content: start;
    }
    
    .parent .child-1 {
        width: 800px;
        background-color: lightgreen;
    }
    
    .parent .child-2 {
      background-color: lightyellow; 
      
    }
    <div class="parent">
      <div class="child-1">Overflowing DIV</div>
      <div class="child-2">Non Overflowing DIV<!-- but does fit to the widest--></div>
    </div>