TL;DR; - how do I restrict a long select element within a table?
I have a legacy system that uses a table (width:100%
) which contains multiple select elements (max-width:100%
).
Some (but not all) of the select elements have very long options which mean that they're wider than the table... it's not possible for me to know which select elements will be effected.
But instead of the table remaining at 100%, and the select reducing in size to fit into the table, it results in the select being full size and forcing the table outside of the client window...
table { width: 100%; }
select { max-width:100%; }
<table border="1">
<tbody>
<tr>
<td>
<select>
<option>Very long option Very long option Very long option Very long option Very long option Very long option Very long option Very long option Very long option Very long option Very long option Very long option</option>
</select>
</td>
</tr>
<tr>
<td>
<select>
<option>Short option</option>
</select>
</td>
</tr>
</tbody>
</table>
One "solution" is to set width:100%
on all the select element, but that would result in the elements with only short options to also be full width, and that is not acceptable...
table { width: 100%; }
select { width: 100%; max-width:100%; }
<table border="1">
<tbody>
<tr>
<td>
<select>
<option>Very long option Very long option Very long option Very long option Very long option Very long option Very long option Very long option Very long option Very long option Very long option Very long option</option>
</select>
</td>
</tr>
<tr>
<td>
<select>
<option>Short option</option>
</select>
</td>
</tr>
</tbody>
</table>
How can I make it so that long selects do not expand the table, without effecting shorter selects?
Because <table>
predates CSS, its layout behaviour has some quirks. One of these is that width
on a <table>
by default acts like min-width
.
This can be overcome by also specifying table-layout: fixed;
on the table:
table {
width: 100%;
table-layout: fixed;
}
select {
max-width: 100%;
}
<table border="1">
<tbody>
<tr>
<td>
<select>
<option>Very long option Very long option Very long option Very long option Very long option Very long option Very long option Very long option Very long option Very long option Very long option Very long option</option>
</select>
</td>
</tr>
<tr>
<td>
<select>
<option>Short option</option>
</select>
</td>
</tr>
</tbody>
</table>
For more info, see: