Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make html table headers span multiple lines

Tags:

html

css

I have some table headers like:

<table>
    <tr>
        <th>
            Invoice Number
        </th>
        <th>
            Invoice Date
        </th>

...

I'm wanting to get the different words on different lines in the headers so I did this:

<table>
    <tr>
        <th>
            Invoice<br />Number
        </th>
        <th>
            Invoice<br />Date
        </th>

...

This works but I'm unsure if it obeys best practises. I have heard on a webcast that you shouldn't really use <br /> anymore and shouldn't use tags to format what your output looks like but should use css so you can change it more easily.

Can anyone suggest a better way to do this?

like image 464
AnonyMouse Avatar asked Nov 02 '11 19:11

AnonyMouse


People also ask

Can an HTML table have multiple header rows?

HTML tables can have headers for each column or row, or for many columns/rows.

How do you make a table with multiple lines on long text in CSS?

When the text in a single table cell exceeds a few words, a line break (<BR>) may improve the appearance and readability of the table. The line break code allows data to be split into multiple lines. Place the line break code <BR> within the text at the point(s) you want the line to break.

How do I combine table headers in HTML?

To merge table columns in HTML use the colspan attribute in <td> tag. With this, merge cells with each other. For example, if your table is having 4 rows and 4 columns, then with colspan attribute, you can easily merge 2 or even 3 of the table cells.


3 Answers

You could code it as:

<table>
    <tr>
        <th>
            <div>Invoice</div><div>Number</div>
        </th>
        <th>
            <div>Invoice</div><div>Date</div>
        </th>

...

Although frankly, I see nothing wrong with that use of the <br /> tag.

like image 168
Eric Avatar answered Oct 13 '22 00:10

Eric


You can set the width for all of your table headers with this:

th {width: 60px;}

or you can assign a class so you just make some of them more narrow:

th.narrow {width: 60px;} 

You can adjust the font size and width as necessary.

Just a side note: don't forget to add scope for accessibility. If the data is below your header cells then use

<th scope="col"> 

and put the th in a thead section and the td cells in the tbody section. If your header cells are on the left side of the table and the cells related to those headers are to the right, then use

<th scope="row">. 
like image 34
PixelGraph Avatar answered Oct 13 '22 01:10

PixelGraph


You could try putting a div inside the th with a specific width and height style to force the second word down.

like image 27
rogerlsmith Avatar answered Oct 13 '22 00:10

rogerlsmith