agri agri - 1 month ago 6
CSS Question

Fixed width for table first column

I have a basic table with scrollable body. Doing that I had to set thead and tbody display:block and I also set the width for th and td.

For some reason the first column th doesn't line up with the first column tds.
Can anyone tell me what causes that?

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

Answer

The width prpoerty for DIV & TABLEs works differantly.

Use max-width & min-width to achieve the results you want:

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 clarify the working of width in HTML, please point out if I get something wrong or missed anything!)

In div width property is used to define the size of element & content is fit accordingly, irrespective of parent & sibling width.

But in case of table, size of element is calculated according to content, & width property gets lower priority. Even sibling size is taken into consideration. Thus we have to use additional properties, like min-width & max-width to force the size we want!