How to set fixed width for <td> in a table ?
The requirement of a table is very normal in the process of designing a web page. HTML provides the <table> tag to construct the table and to define rows and columns <tr> and <td> tags respectively are used.
By default, the dimensions of the rows and columns in a table are adjusted by the browser automatically in a way that fits the contents. However, there can be situations where the width of the columns are needed to be fixed. There are multiple ways to fix the width for <td> tag. Some of them are mentioned below:
- 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. The width attribute is invalid and has been disapproved, thus it is no longer supported by HTML5.
- Using CSS: The Cascading Style Sheet(CSS) is widely used to decorate the web pages which are of vast sizes. By using CSS, the styling of HTML elements is easy to modify. To fix the width of td tag the nth-child CSS is used to set the property of specific columns(determined by the value of n) in each row of the table .
- Using col tag and fixing the table layout property: If the same kind of column property is to be followed in every row of a table then using col tag to define the properties of the column is a great idea. If the col tag is written in the HTML document for the first time and its attributes are set, those all property refers to the first column of each row of the table inside which it is mentioned. Similarly using col tag for the second time and defining its attributes make its impact on the second column of each row of the table. Moreover, to adjust the long texts inside the columns CSS property table-layout:fixed; is used.Below is the implementation.
- Output: The output will be same for every method.
Attention reader! Don’t stop learning now. Get hold of all the important Comcompetitivepetitve Programming concepts with the Web Design for Beginners | HTML course.