Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Table - Both fixed and multiple variable column widths

I have to build a table with 5 columns. The table width is variable (50% of content width). Some columns contain fixed-size buttons, so those columns should have a fixed with, say 100px. Some columns have text in them, so I want those columns to have variable column widths.

For example:

Column1: 20% of (tablewidth - sum(fixedwidth_columns))'

Column2: 100px

Column3: 40% of (tablewidth - sum(fixedwidth_columns))

Column4: 200px

Column5: 40% of (tablewidth - sum(fixedwidth_columns))

What is the best way to achieve this?

like image 661
Basaa Avatar asked Feb 08 '14 21:02

Basaa


People also ask

Is it allowed to use different column widths in HTML?

HTML tables can have different sizes for each column, row or the entire table. Use the style attribute with the width or height properties to specify the size of a table, row or column.

How do you make all columns the same width in HTML?

Just add style="table-layout: fixed ; width: 100%;" inside <table> tag and also if you do not specify any styles and add just style=" width: 100%;" inside <table> You will be able to resolve it.

How do I make columns with different widths in a table?

Change column and row width To change the width, do one of the following: Select the boundary of the column or row you want to move and drag it to the width or height you want. Select the rows or columns and then select Layout and choose your height and width.

Can one cell in a table stretch over two columns HTML?

The colspan attribute in HTML specifies the number of columns a cell should span. It allows the single table cell to span the width of more than one cell or column.


2 Answers

You could set the table-layout: fixed for the table element, then simply set width attribute on relevant <td> or <th> elements:

table {
    table-layout: fixed;
}

JSFiddle Demo.

From the MDN:

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

Values:

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.

like image 123
Hashem Qolami Avatar answered Sep 17 '22 22:09

Hashem Qolami


to fixed width in a table, you need the table-layout propertie set to fixed; Since you mix % and px , it will not be coherent .

You may set only the px width and eventually a small value of % and let other column to use width left avalaible. example : http://jsfiddle.net/M4Et8/2/

<table style='table-layout:fixed;width:100%' border='1'>
    <tr>
        <th style='width: 20%;'>Column1</th>
        <th style='width: 100px;'>Column2</th>
        <th >Column3</th>
        <th style='width: 200px;'>Column4</th>
        <th >Column5</th>
    </tr>
</table>
like image 37
G-Cyrillus Avatar answered Sep 19 '22 22:09

G-Cyrillus