The HTML <td> width attribute is used to specify the width of a table data cell.
- The width can be given in pixels or percentage.
- It controls how wide the table cell appears.
- In modern HTML, CSS width property is preferred instead of the width attribute.
Syntax:
<td width="pixels | %">- pixels: It sets the width of the table in terms of pixels.
- %: It sets the width of the table in terms of percentage (%).
Note: The <td> width Attribute is not supported by HTML5.
Example 1: Using Pixels for <td> Width
In the following example, we set the width of the first column in pixels.
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>
HTML td width Attribute
</title>
</head>
<body>
<center>
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h3 style="color: crimson;">
HTML td width Attribute
</h3>
<!--Driver Code Ends-->
<table border="1" width="500">
<tr>
<th>NAME</th>
<th>AGE</th>
<th>BRANCH</th>
</tr>
<tr>
<td width="50%">Ben</td>
<td width="20%">22</td>
<td width="30%">CSE</td>
</tr>
<tr>
<td>Ron</td>
<td>25</td>
<td>EC</td>
</tr>
</table>
<!--Driver Code Starts-->
</center>
</body>
</html>
<!--Driver Code Ends-->
Example 2: Using Percentage for <td> Width
In this example, we set the width of the first column as a percentage of the total table width.
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>
HTML td width Attribute
</title>
</head>
<body>
<center>
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h3 style="color: crimson;">
HTML td width Attribute
</h3>
<!--Driver Code Ends-->
<table border="1" width="80%">
<tr>
<th>NAME</th>
<th>AGE</th>
<th>BRANCH</th>
</tr>
<tr>
<td width="40%">Ben</td>
<td width="30%">22</td>
<td width="30%">CSE</td>
</tr>
<tr>
<td width="60%">Ron</td>
<td width="20%">25</td>
<td width="20%">EC</td>
</tr>
</table>
<!--Driver Code Starts-->
</center>
</body>
</html>
<!--Driver Code Ends-->
HTML5 Deprecation Notice
The <td> width attribute is deprecated in HTML5 and is no longer recommended for modern web development. Instead of using the width attribute, developers should use CSS to set the width of table cells for better styling, flexibility, and responsiveness.
Here’s an example of how to set the width of a table cell using CSS:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table Cell Width Using CSS</title>
<style>
td {
width: 200px; /* Example of setting width in CSS */
}
</style>
</head>
<body>
<table border="1">
<tr>
<td>Cell with width set using CSS</td>
<td>Another cell</td>
</tr>
<tr>
<td>Cell with width set using CSS</td>
<td>Another cell</td>
</tr>
</table>
</body>
</html>