Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Table - max-width not working on td descendants

Tags:

I have table with width: 100% and an element in that table with width: 40em; max-width: 100%, but the element is still stretching the table when the browser window gets too small.

I want this element to be a fixed width but not be larger than the container if the container gets too small. If there's not enough room for the fixed width, max-width: 100% should make it smaller to fit the available space. This works outside of a table.

Note that the max-width is not on the table itself. It is actually on an <input> element, although the code I've linked includes a separate table with the same problem on a <span> element. It also includes an <input> field outside of the table which behaves correctly.

link to jsfiddle

like image 980
meustrus Avatar asked Oct 19 '12 16:10

meustrus


People also ask

How fix TD table width?

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 give equal width to all TD tables?

Using table-layout: fixed as a property for table and width: calc(100%/3); for td (assuming there are 3 td 's). With these two properties set, the table cells will be equal in size.

How do you define td width in HTML?

To set the cell width and height, use the CSS style. The height and width attribute of the <td> cell isn't supported in HTML5. Use the CSS property width and height to set the width and height of the cell respectively. Just keep in mind, the usage of style attribute overrides any style set globally.

How do I keep my table width fixed in HTML?

The width of the columns i.e. td in a table can be fixed very easily. This can be done by adding the width attribute in the <td> tag. If the width is not specified, the width of the column changes according to the change in the content.


1 Answers

You should use table-layout: fixed for the table element to get the max-width properties of <td>'s descendants to work.

From the MDN:

The table-layout CSS property defines the algorithm to be used to layout the table cells, rows, and columns.

fixed value:
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.

table {     table-layout: fixed; } 

WORKING DEMO.

like image 149
Hashem Qolami Avatar answered Jan 03 '23 12:01

Hashem Qolami