Search code examples
csssassflexboxcss-selectorstailwind-css

Make a DIV to take the remainder of the parent's width -AND- to also take the parent's height


We have this markup:

<div class="parent">
   <div class="child-1">
      Hello World!
   </div>
   <div class="child-2">
   </div>
</div>

child-1 width is 30%, and we need child-2 to take the remainder of the parent's width, so we have:

.child-1{
   width:30%;
}
.child-2{
   float: none;
   overflow: hidden;
}

And it works. But we also need child-2 to take the parent's height, so we added flex to the parent:

.parent{
   display:flex
}

And it works. However, child-2 is no longer taking the reminder of the parent width.

If we define child-2 width to a fixed number, such as 70%, it works. However, for the script we are doing, we need it to take the remainder of the parent with.

Is there a way to make child-2 to take the remainder of the parent width -AND- to take the parent height without having to defined its width to a fixed number?


Solution

  • Yes, you can make child-2 take the remaining width of the parent and also take the parent's height without specifying a fixed width. You can achieve this using the "flex-grow" property. Here's how to do it:

      .parent {
           display: flex;
        }
        
        .child-1 {
           width: 30%;
        }
        
        .child-2 {
           flex-grow: 1; /* This will make it take the remaining width */
           overflow: hidden;
        }
    

    By setting flex-grow to 1 for child-2, it will automatically expand to fill the remaining width of the parent while still taking the parent's height. This way, you don't need to specify a fixed width for child-2, and it will adapt to the available space in the parent container.