Explain Codes LogoExplain Codes Logo

Fixed Table Cell Width

html
responsive-design
css
table-layout
Anton ShumikhinbyAnton Shumikhin·Oct 27, 2024
TLDR

Set a specific pixel width in CSS to pin the cell width in an HTML table:

.fixed-width-cell { width: 100px; /* Change to your desired width */ }

Use this class in your <td>:

<td class="fixed-width-cell">Your content here</td>

Ensure consistent cell sizes across your table with table-layout: fixed; for your <table>:

table { table-layout: fixed; /* Hey, where's my content? */ }

Use the <col> to define column widths precisely:

<table> <colgroup> <col style="width: 100px;"> <col style="width: 200px;"> </colgroup> <!-- Your rows with <td> elements go here --> </table>

Prevent text spillage with overflow: hidden; and word-wrap: break-word; on td:

.fixed-width-cell { overflow: hidden; word-wrap: break-word; /* Break, damn you! */ }

Advanced techniques

Content management with div

Encase your cell content in <div> tags. This helps to better handle overflow and keeps the fixed width intact:

<td class="fixed-width-cell"> <div style="overflow: hidden; word-wrap: break-word;"> Your super long content that loves to escape </div> </td>

Selective column targeting

Use nth-of-type CSS selector to modify widths of specific columns:

table tr th:nth-of-type(1), table tr td:nth-of-type(1) { width: 150px; /* Because size matters */ }

Emulating jqGrid

Emulate jqGrid behavior by coupling table-layout: fixed with specific width to <col> or <th> elements:

table.jq-grid { table-layout: fixed; /* I’m fixed, are you? */} table.jq-grid col { width: 120px; /* Stay in line */}

Tricky scenarios and solutions

Understanding table layout property

When table-layout: is set to fixed;, content size is ignored and column widths are determined by the first row, <col>, or <th> elements, this could potentially hide data if not handled properly.

Balancing overflow and visibility

Overflow: hidden; may obscure overflowing content. When you need to retain visibility, consider using overflow: auto; or adjust cell widths accordingly.

Setting cell widths

Ensure all columns have their widths set, to avoid disproportionate column sizing.

Being responsive

To retain a fluid layout across varying screen sizes, use percentage values or viewport units instead of pixel values. Media queries can be handy to adjust table designs according to devices.