Explain Codes LogoExplain Codes Logo

Css table td width - fixed, not flexible

html
responsive-design
css
web-development
Alex KataevbyAlex Kataev·Dec 22, 2024
TLDR

To enforce a fixed width for td cells, implement table-layout: fixed; on your table and specify a width on your td styles. This prevents the cells from stretching and ensures a consistent table layout.

<style> table { table-layout: fixed; } /* Locking the width */ td { width: 200px; overflow: hidden;} /* Meet the enforcer */ </style> <table> <tr> <td>Locked width</td> <td>Won't budge</td> </tr> </table>

Using table-layout: fixed;, the 200px width is strictly adhered to, unaffected by the amount of content.

Dealing with lengthy content

When the content surpasses the fixed cell width, clever use of text-overflow: ellipsis adds an ellipsis (...) in place of the omitted content:

<style> td { white-space: nowrap; /* No wrapping please */ text-overflow: ellipsis; /* Too long? Show '...' */ } </style>

This results in a well-groomed visual impression, indicating there is more content that isn't shown.

Maintaining strict boundaries

To have stringent width parameters, set both min-width and max-width to identical values:

td { min-width: 200px; /* No lesser than this */ max-width: 200px; /* Not a pixel more */ }

This ensures the cell width is confined within these limits, without any shrink or bulge.

Cell-spacing minus the compromise

The cellpadding and cellspacing attributes can provide space within and around cells, respectively, without undermining the fixed width:

<table cellspacing="5" cellpadding="5"> <!-- Fill me up --> </table>

These attributes offer quick fixes, though they use outdated HTML. Consider using CSS for maintaining modern standards.

Tailoring fixed-width cells

Curbing text spill-over

To prevent lengthy text from overflowing into the next line, pair display: inline-block with white-space: nowrap.

Customizing text visibility

If the content isn't fitting well within the cell, try tweaking the font-size or font-family:

td { font-size: 0.9em; /* Make it fit without squashing */ }

This adjustment ensures that long text fits comfortably within fixed-width cells.

Compatibility check

Do verify cross-browser compatibility of your CSS code. Though most modern browsers support these properties, older versions might have compatibility issues.