Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it different putting the width style in the first <td>s or the second in an html table / Why are these tables rendered differently?

Tags:

Can you explain why these two HTML codes result in different look when rendered? fiddle1 and fiddle2

The only difference in the code is that in fiddle1 style="width: 50px;" is in the first row of the table, while in fiddle2 it is in the second row. But this results in different widths for each one.

According to Chrome Dev Tools fiddle1 both cells/columns have 51px width (should be 50px anyways), and in fiddle2 the first cells/columns have 49px width and the second 50px width.

Markup in Fiddle 1

<table>
   <tr>
      <td style="width: 50px;">Test</td>
      <td style="width: 50px;">Testing 1123455</td>
   </tr>
   <tr>
      <td>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA</td>
      <td>B</td>
   </tr>
</table>

Markup in Fiddle 2

<table>
   <tr>
      <td>Test</td>
      <td>Testing 1123455</td>
   </tr>
   <tr>
      <td style="width: 50px;">AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA</td>
      <td style="width: 50px;">B</td>
   </tr>
</table>

CSS for both fiddles

table {
  table-layout: fixed;
  width: 100px;
}

td {
  border: 1px solid black;
  overflow: hidden;
}
like image 210
Benur21 Avatar asked Aug 05 '17 17:08

Benur21


1 Answers

That is the magic of 'table-layout: fixed'.
As specified in this link

The table-layout CSS property specifies the algorithm used to lay out cells, rows, and columns.

When the value is 'fixed': Table and column widths are set by the widths of table and col elements or by the width of the first row of cells. Cells in subsequent rows do not affect column widths.

In your first case: As you specified the width for columns of first row. Rendering algorithm takes the width and renders it with that width. The extra 1px you see, is just the border width.

In Second Case: As there is no width for first row specified. It takes the table width and try to adjust the row columns in it. As for two columns there will be three borders, we left with the 97px to be divided among the two columns. As pixel cannot be divided into decimals, you get 48px and 49px width of columns. extra 1px is for the border width

like image 66
sanjiv saini Avatar answered Oct 11 '22 12:10

sanjiv saini