Create a table with fixed cells width




Create a table with cells width exactly you need is some more difficult than it may be seemed at once. So, if you need to make a table 300 pixels width with 5 cells same width, than cell width should be no more than 60 pixels. Of course, you should remember about borders and paddings in cells.

If you just make table like this, your cells width can be more or less than 60 pixels.

Now I’ll show you how browser renders a table.

I create a table in HTML and fill its cells with some words:

 

If I use these styles for table

 

I expect that td width is 60 pixels, but in fact I have a picture where td width differs from 60 pixels and it's not the same.

Drawing 1. Table with incorrect width of cells

Drawing 1. Table with incorrect width of cells

By default parameter table-layout has value "auto" and it’s result is on the drawing 1 with incorrect width. With table-layout value "auto" browser generates cells width automatically according to text inside them. Browser makes cell width only about asked width but not exact.

To make exact cell width you need to add CSS-parameter table-layout: fixed; for a table.

So if we write these styles

 

Drawing 2. Table cells with fixed size

Drawing 2. Table cells with fixed size

We have a table with cells width 60px (Drawing 2). But our words in cells went out of borders and it’s not very pretty. To avoid it, you need to add attribute "overflow" with value "hidden" to all cells in a table. The result is below:

 

 

 

Drawing 3. Cells with fixed size but with cut words

Drawing 3. Cells with fixed size but with cut words

If you use "overflow: auto; " the result is as in the drawing 4.

Drawing 4. Cells with fixed size with scroll where it’s asked

Drawing 4. Cells with fixed size with scroll where it’s asked

 



MarkiMarta.com. Notes of web-specialist
Since 2009
18+