Home >Web Front-end >Front-end Q&A >Set table width html
In HTML, we can use the f5d188ed2c074f8b944552db028f98a1
tag to create a table. When creating a table, you often need to set the width of the table to fit the page layout or display content.
There are two ways to set the width of the table in HTML:
Method 1: Using CSS styles
We can use CSS styles to set the width of the table. The advantage of using CSS styles is that you can separate the table width from the HTML text content, improving the maintainability and readability of the code.
Here is an example:
<style> table { width: 50%; /* 设置表格宽度为页面宽度的50% */ border-collapse: collapse; } th, td { padding: 5px; border: 1px solid #ccc; } </style> <table> <tr> <th>姓名</th> <th>年龄</th> <th>性别</th> </tr> <tr> <td>张三</td> <td>25</td> <td>男</td> </tr> <tr> <td>李四</td> <td>30</td> <td>女</td> </tr> </table>
In the above example, we used CSS styles to set the width of the table to 50% of the page width. We also set the border-collapse
attribute to merge the table borders and increase the beauty of the table. At the same time, we can use the th
and td
selectors to set the style of the table header and cells.
Method 2: Using HTML attributes
We can also use HTML attributes to set the width of the table. Although this method is relatively simple, the code may not be clear enough when using multiple HTML attributes to set the table width.
The following is an example:
<table width="50%" border="1"> <tr> <th>姓名</th> <th>年龄</th> <th>性别</th> </tr> <tr> <td>张三</td> <td>25</td> <td>男</td> </tr> <tr> <td>李四</td> <td>30</td> <td>女</td> </tr> </table>
In the above example, we use the HTML attributes width
and border
to set the width and width of the table respectively. frame. It is worth noting that when using HTML attributes to set the table width, you can use percentage
, pixel value
, em
and other units.
To sum up, we can use CSS styles or HTML attributes to set the table width. The specific method is selected according to the needs. However, for the maintainability and readability of the code, it is recommended to use CSS styles to set the table width.
The above is the detailed content of Set table width html. For more information, please follow other related articles on the PHP Chinese website!