Search code examples
htmlcssflexbox

Text truncate with percentage width in parent container


I have 4 columns each having 25% width. It keeps the column width as expected when I want to add a long text without truncating. However, truncating suddenly increases all of the columns' length. The followings fix the problem:

  • using grid layout instead of flex-row (But I want to keep the num. of columns dynamic)
  • removing the top-most container's flexbox property (But it breaks the other part of the design)

Any solution or explanation of the root cause would be much appreciated.

Here is the html with tailwind-css

JSFiddle

<div class="h-screen flex flex-row">
  <div class="w-15 flex items-center -rotate-90">
    Sidebar
  </div>
  <div class="flex flex-col flex-1">  
    <div class="flex mx-auto items-center h-14">
      Header
    </div>
    <div class="flex flex-1 flex-row ">    
      <div class="w-1/4 bg-blue-200 truncate">
        When this text is too long to fit in the container, it truncates but column lengths are iincreased with the text length and columns don't fit to the screen. Removing the truncate class also fixes the problem.
      </div>
      <div class="w-1/4 bg-red-200">
      Second Column
      </div>
      <div class="w-1/4 bg-green-200">
      Third Column
      </div>
      <div class="w-1/4 bg-orange-200">
      Fourth Column
      </div>
    
    </div>
  </div>
  
</div>


Solution

  • keep these in mind as a rule of thumb: 1- use flex if you want the CHILDREN to take control, not the parent wrapper. 2- use grid if you want the PARENT to control the children.

    in your case, your concern is to keep the width of the columns and the text must keep itself inside, it should go to the next line if it hits the edge of the column right? then you should use grid and to keep the dynamic number of columns use auto-fit which will create a new column for you when needed.

    try and change it to this :

    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(min(25%, 100%), 1fr) );
    

    this part minmax(min(25%, 100%), 1fr) is basically for responsiveness, so when there is no enough space for each column to take 25% of the parent, the columns will take the width of 100% and they'll be stack after each other in one column.

    sorry it's not using tailwind but I hope it works for you