Fixed width for the first column of the table

I have a scrollable body base table. Having done this, I had to set the display to "thead" and "tbody": block, and also set the width for th and td.

For some reason, the first column of th does not match the first column of tds. Can someone tell me what causes this?

CSS

thead, tbody { display: block; } thead { text-align: left; } tbody { background: yellow; overflow-y: auto; height: 6em; } thead th, tbody td { width: 4em; padding: 2px; } thead tr th:first-child, tbody tr td:first-child { width: 8em; background: salmon; font-weight: normal; } 

Here is the fiddle

+5
source share
2 answers

The prpoerty width for DIV and TABLE works differently.

Use max-width and min-width to achieve the desired results:

 thead tr th:first-child, tbody tr td:first-child { width: 8em; min-width: 8em; max-width: 8em; word-break: break-all; } 

Edit:

(Editing the answer clarifies the work of width in HTML, please indicate if there is something wrong or something is missing!)

In the div property, width is used to determine the size of the element, and the content matches accordingly regardless of the width of the parent and native languages.

But in the case of a table, the size of the element is calculated according to the contents, and the width property gets a lower priority. Even the size of the brother is taken into account. Thus, we must use additional properties such as min-width and max-width to force the desired size!

+12
source

remove your first style rule: display: block from tbody and thead

Through this, you drag the formatting and layout of the table that display: the table provides

 thead, tbody { // display: block; } 

Fixed

0
source

Source: https://habr.com/ru/post/1258698/


All Articles