Method 1: Using HTML “width” Attribute
The “width” is a basic attribute provided by HTML. It sets the width or horizontal length of the HTML element. To fix table data, the width attribute is utilized in the below steps.
Step 1: Create a Table
In the HTML file, use a “<center>” tag to display each element inside it in the center of the webpage. Inside it, construct a table using the “<table>”,”<tr>” and “<td>” tags and write data in it:
Step 2: Add CSS Properties to “table” Element
Use the table element selector in CSS and add the “border” of 1px solid red, “text-align” aligns the text to the center, and “width” that sets the overall width of the table to 80%:
border: 1px solid red;
text-align: center;
width:80%; }
Step 3: Assigning Properties to “td” Element
Use the “td” element selector and sets the “border-bottom” of 5px solid red, “padding” of 20px to make the item more prominent, and “width” sets as 30%:
border-bottom: 5px solid red;
padding:20px;
width:30%;
}
Step 4: Assigning Properties to “th” Element
Use the “th” element selector to change the color of “border-bottom” from red to sea green to create a better visualization:
border-bottom: 5px solid seagreen;
padding:20px;
width:30%;
}
Output is displayed as:
The above snapshot shows that all column’s widths are fixed at 30% each.
Method 2: Using the “nth-child( )” Selector
The nth-child() property of CSS is used to create a fixed-width table. This property gets the column number and selects the “<td>” and “<th>” tags. For instance, the width is “fixed” for only column numbers “1” and “3”. Each of these columns is getting a width of 10%. This article has successfully demonstrated how to fix the data table width.
width: 10%;
}
th:nth-child(1){
width: 10%;
}
The output of the above code block is:
This output displays that column numbers 1 and 3 are fixed to the width of 10%.
Method 3: Using <col> Tag
Inside the “table” section in the CSS portion add the “table-layout: fixed” property to set the “width” of data table elements:
table-layout: fixed;
width:80%;
border: 1px solid red;
text-align: center;
}
In the HTML file, add the “<col>” tag inside the “<table>” section. For instance, fix the width of 15% to the first column and 30% to the second column:
After executing the above code snippet, the output is:
That is how the user can fix the width of table data <td> elements.
Conclusion
To fix the width of the table data, use the “width” attribute, “nth-child( )” separator, and “<col>” tag methods. The “width” property sets the fixed width. The “nth-child( )” separator gets the column number as a parameter. Furthermore, the “<col>” tag can be used to make the table not flexible. This article has demonstrated how to fix the width of table data <td> elements.