Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed width for table first column

Tags:

html

css

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

like image 350
agri Avatar asked Oct 24 '16 08:10

agri


People also ask

How do you set a fixed column width?

On the Layout tab, in the Cell Size group, click AutoFit. Click Fixed Column Width.

How do you set the fixed width of a TD table?

Using width attribute: The <td> tag has width attribute to control the width of a particular column. By assigning a numeric value to this attribute between 0 to 100 in terms of percentage(or you can use pixel format). We can restrict the column width up to that much percentage of the table's total width.

How do you change column width to fit the constant?

Resize columns Select a column or a range of columns. On the Home tab, select Format > Column Width (or Column Height). Type the column width and select OK.


1 Answers

The width property for DIV & TABLE works differently.

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 got something wrong or missed anything!)

In divs the width property is used to define the size of the element and the content is fitted in accordingly, irrespective of parent and sibling width.

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

like image 100
demonofthemist Avatar answered Oct 03 '22 10:10

demonofthemist