Specifically, what I’m trying to achieve is this (try to imagine it without the table borders):
where:
- the first column is fixed width and has a
<hr>
element the full column width. - the second column has the text of the title, and the column width expands to suit.
- the third column has a width that uses all remaining table width and has a
<hr>
element the full column width.
I got this far:
<table border="1" cellpadding="1" cellspacing="1" style="table-layout: fixed; width:100%;">
<tr>
<td style="width:40px;"><hr></td>
<td style="white-space: nowrap;overflow: hidden;"><strong>Some Title</strong></td>
<td style="width:90%"><hr></td>
</tr>
</table>
but this plainly is only "correct" for one table width, and incorrect for all others:
How can I prevent column 2 from being overwritten by column 3, or force column 3 to only use as much width as it needs?
4
Answers
Changing
table-layout: fixed
totable-layout: auto
and then adding amin-width: 40px
to your first columns andwidth: 100%
to your 3rd columns should do the trick.Doing so, the last column will fill the available space.
One thing should be noted: Tables are "stiff", so as far as I know it’s not possible to give the 3rd column a different width for each row.
See the below example, where the 2nd column "pulls" away the 3rd column to fit the longest row:
Just add
width: max-content;
to the second column:If you just want to create this effekt "header with line in background" variants like this one might be an alternative for responsive designs:
Using a table for this purpose is really inadequate semantically. Instead, you can use a flex container with three children and the following settings which will also solve your width problems:
If you want the horizontal lines higher, add
position: relative
and abottom
value to the spans:I recommend not using a
<table>
element for data that is not tabular (if you are showing tabular data in the<table>
, and this is a heading for that<table>
, then use the<caption>
element to contain that heading).So, instead of that table approach, I’d suggest the following, using a semantic
<header>
element along with CSS flex layout:JS Fiddle demo.