Tables are a complex thing to create in a webpage. Four different tags are involved in making a table. CSS works great for styling a table because it specifies different properties for different tags. Following are the properties available in CSS for tables:
Property | Value | Used On | Description |
Border | 1px solid black; | Table, tr, th, td | Border of table. Here 1px is thickness, solid is type (solid/dotted/dashed) and black is color |
border-collapse | Separate; | Table, tr, th, td | Separate borders |
collapse; | Table, tr, th, td | Collapsed borders | |
border-bottom / border-top / border-left / border-right | 1px solid #000000; | Table, tr, th, td | Border of particular side |
Width | 100%; | table | Width of table as per the width of parental container |
500px; | table | Fixed width of table | |
Height | 50px; | tr, th, td | Height of table elements |
text-align | left; / right; / center; | Table, tr, th, td | Horizontal Alignment of text in table |
vertical-align | bottom; / top; / middle; | tr, th, td | Vertical Alignment of text in table |
Padding | 15px; / 15px 15px; / 15px 15px 15px; / 15px 12px 15px 12px | th, td | Space between boundary and element |
background-color | #4CAF50; | Table, tr, th, td | Background color of table elements |
background-image | url("paper.gif"); | background-image | |
color | white; | Table, tr, th, td | Text color of table elements |
tr:nth-child(odd) {background-color: #f3f3f3;}
tr:nth-child(even) {background-color: #f2f2f2;}
tr:hover {background-color: #f5f5f5;}
nth-child(odd)
and nth-child(even)
both can be used to create a stripped table. hover
state can be used with individual th
and td
as well.
Usually a responsive element is the one that changes its size as per the width of the display device but in case of tables, its a little different. A responsive table does not changes its size. Instead it gives a horizonal scroll bar to scroll to the entire width of the table.
... table content ...
Example 1: Simple table with border, width, height and align
Example 2: Another table with background-image, background-color, and padding
Example 3: A table with nth-child() and hover states
Example 4: A responsive table