We have alreay learned HTML Tables that is very basic there we learned how to create HTML table and how to make rows cols in HTML Table.
To Make a beautiful HTML table we apply CSS on HTML Table.
CSS has the following properties for styling the HTML Tables:
- border
- border-collapse
- width
- height
- text-align
- vertical-align
- padding
- :hover
- background-color (rows and headers)
- overflow
border
The border can be set for <table>, <th> (table header) and <tr> (table tow). It can be set together by using grouping selectors or even individually as per requirements.
1 2 3 | table,th,td { border: 1px solid green; } |
border-collapse
By using just the border property for all table, th and tr, you might get double borders which may or may not be desirable.
1 2 3 4 | .collapse{ border-collapse:collapse; } </p> |
The border-collapse property tells whether these multiple borders should collapse into one. The value collapse is given to this property in case we need single border around the table elements.
Table width and height
The width and height properties can be used for this purpose. The values can be specific like in pixels or relative like percentage.
1 2 3 4 5 6 7 8 9 | table{ width:90%; height:150px; border:1px solid green; } th,td{ border:1px solid green; } |
text-align
The default text alignment for <th> content is center and that for the <td> content is left. For other alignments we can use the text-align property for both <th> and <td>.
vertical-align
The default vertical alignment for both <th> and <td> content is middle. To change it to top or bottom, we can use the vertical-align property.
padding
The padding property can be used to provide space between border and content of <td> and <th>. Additionally, you can use the border-bottom property to give horizontal lines separating the rows.
:hover
To provide effects on mouse hover, this property can be used. You this property is used with the desired elements like tr:hover or th:hover. You can then use it to highlight the table elements.
nth-child()
The nth-child() selector can be used to give striped rows for the table. The values even or odd are passed to highlight the even or odd rows accordingly.
background-color
The property can be used to control the background colors. It can be directly used like for other elements or it can be used with nth-child() or hover, to provide background colors for specific rows or in specific condition.
overflow-x
This property makes the table responsive in case its horizontal size gets larger than the browser or the containing element. If you set overflow-x as auto, a scroll-bar will be added every time the size overflows.