Home > front end >  How to use CSS to limit Table Header to 2 lines
How to use CSS to limit Table Header to 2 lines

Time:11-25

Limiting to a line would be simple using white-space:nowrap but I have a specific problem where I would like to force my header text to fit in a specific width.

I had success adding individual style on the element to force them to the specific 2 lines I want but it does not seem like a long term solution.

e.g.

<table >
        <thead>
            <tr>
                <th>Lorem ipsum</th>
                <th>Lorem ipsum</th>
                <th>Lorem ipsum</th>
                <th>Lorem ipsum</th>
                <th>Lorem ipsum</th>
                <th style="min-width: 90px">Lorem ipsum dolor sit amet</th>
            </tr>
        </thead>
</table>

Another way I tried was to include break points in the text itself but I also don't want to go through the multiple files to do so.

<th>Lorem ipsum <br /> dolor sit amet</th>

I have also tried adding a external style sheet to force the min-width of all to a value but this causes huge gaps in-between the table headers.

Would like to know if there's a better method to do this.

CodePudding user response:

You should use the max-width property on all the headers. The amount of headers multiplied by the chosen width will amount to the maximum width of the table.

Here's an example of max-width which with 6 headers as per your example amounts to a maximum of 300px.

thead th {
    max-width: 50px
}

CodePudding user response:

You can use the css line-clamp property.

HTML

<table >
        <thead>
            <tr>
                <th><span class='table-header-limit'>Lorem ipsum</span></th>
                <th><span class='table-header-limit'>Lorem ipsum</span></th>
                <th><span class='table-header-limit'>Lorem ipsum</span></th>
                <th><span class='table-header-limit'>Lorem ipsum</span></th>
                <th><span class='table-header-limit'>Lorem ipsum</span></th>
                <th><span class='table-header-limit'>Lorem ipsum dolor sit amet amet amet Lorem ipsum dolor sit amet amet amet Lorem ipsum dolor sit amet amet amet</span></th>
            </tr>
        </thead>
</table>

CSS

.table-header-limit {
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

Output enter image description here

  • Related