Search code examples
htmlcssdynamicwidth

Set width of the right div based on left div


I have a markup where I have a container of lets say width 100% and I have two child elements in this container. The first child has a width based on the text inside of this div then the next div should have a (width of the container's width) - (the first child element).

See image below for clarification:

enter image description here

In this case the white box has a width of 100% and has a width based on its text content. The green div should have the (width of white box) - (red box width).

How do I do set the green width in CSS? This is what I have tried so far:

.ContentItemMenu {
  width: 100%;
  height: 50px;
  /* background-color: bisque; */
  border-bottom: 1px solid #c3c3c3;
}

.ContentTitle {
  width: auto;
  padding: 0 20px;
  height: 100%;
  float: left;
  font-size: 25px;
  font-family: opensansBold;
  text-align: left;
  line-height: 50px;
  background-color: #5144F0;
}

.SubContentTabs {
  width: 100%;
  height: 100%;
  float: left;
  background-color: aquamarine;
}
<div class="ContentItemMenu">
  <div class="ContentTitle">Some text</div>
  <div class="SubContentTabs"></div>
</div>

I am a complete newb to css, so if more clarification is needed let me know.


Solution

  • Use a flexbox - add display: flex to the ContentItemMenu and set flex: 1 to SubContentTabs - see demo below:

    .ContentItemMenu {
      display: flex; /* ADDED */
      width: 100%;
      height: 50px;
      /* background-color: bisque; */
      border-bottom: 1px solid #c3c3c3;
    }
    
    .ContentTitle {
      width: auto;
      padding: 0 20px;
      height: 100%;
      float: left;
      font-size: 25px;
      font-family: opensansBold;
      text-align: left;
      line-height: 50px;
      background-color: #5144F0;
    }
    
    .SubContentTabs {
      width: 100%;
      height: 100%;
      float: left;
      background-color: aquamarine;
      flex: 1; /* ADDED */
    }
    <div class="ContentItemMenu">
      <div class="ContentTitle">Some text</div>
      <div class="SubContentTabs"></div>
    </div>
    <br/>
    <div class="ContentItemMenu">
      <div class="ContentTitle">Some text here, this is a long text</div>
      <div class="SubContentTabs"></div>
    </div>