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:

<table cellpadding="0" cellspacing="0" border="0">
 <tr>
    <td>cellspacing</td>
    <td>cellpadding</td>
    <td>border</td>
    <td>width</td>
    <td>prerequisites</td>
 </tr>
</table>

 

If I use these styles for table

  table 
  {
      width: 300px;
      border-left: #000 1px solid;
      border-bottom: #000 1px solid;
  }

  table td
  {
      width:20%;
      padding: 0px;
      border-right: #000 1px solid;
      border-top: #000 1px solid;
  }

 

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

  table 
  {
      width: 300px;
      border-left: #000 1px solid;
      border-bottom: #000 1px solid;
      table-layout: fixed;
  }

  table td
  {
      width:20%;
      padding: 0px;
      border-right: #000 1px solid;
      border-top: #000 1px solid;
  }

 

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:

 

  table 
  {
      width: 300px;
      border-left: #000 1px solid;
      border-bottom: #000 1px solid;
      table-layout: fixed;
  }

  table td
  {
      width:20%;
      padding: 0px;
      border-right: #000 1px solid;
      border-top: #000 1px solid;
      overflow: hidden;
  }

 

 

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

 




No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment





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