CSS Tables

Welcome to the world of CSS tables—your gateway to crafting visually appealing and organized tabular data on web pages. From adding borders, adjusting space, and precise styling to managing dimensions and creating responsive designs. Explore the nuances of aligning text, controlling table layout, and enhancing visual elements. Let's delve into the art of styling tables with CSS for a seamless and engaging user experience.


Styling Tables with CSS

Tables are commonly used to present tabular data, particularly financial reports. However, if tables are created without any styles or attributes, browsers display them without borders. To enhance the appearance of your tables, CSS can be used.

CSS offers several attributes for controlling the layout and display of table components. In the following section, you will learn how to create stylish and consistent tables using CSS.


Adding Borders to Tables

The best technique to define table borders is to use the CSS border attribute. For example, The following code will set a blue border for the table, th, and td elements.

<style>
table, th, td {
    border: 2px solid blue;
}
</style>

Collapsing Table Borders

By default, browsers generate a double border around the table and its cells, leaving some space in between. To eliminate this double border issue and create clean, single-line borders, you can collapse the neighboring table cell borders.

In CSS, there are two methods for establishing table cell borders: separate and collapse. The default method is separate where each table cell has its own individual border.

However, you can use the CSS border-collapse property to switch to the collapse method, where nearby table cells share a single border. The following style rules demonstrate how to collapse the table cell borders and apply a one-pixel black border:

<style>
table {
    border-collapse: collapse;
}
table, th, td {
    border: 5px solid blue;
}
</style>

To remove the gap between table cell borders, you can set the CSS border-spacing property to "0". However, this only removes the gap and does not combine the borders like the border-collapse: collapse method.


Adjusting Space inside Tables

By default, table cells are rendered to be just large enough to accommodate the data inside them. You can use the CSS padding property to add additional space between the table cell contents and the cell borders. Here's an example:

<style>
table {
    border-collapse: collapse;
}
table, th, td {
    border: 5px solid blue;
}
th, td {
    padding: 20px;
}
</style>

If your table's borders are separated, you can also use the CSS border-spacing property to adjust the spacing between the cell borders, which is the default behavior. The following style rules add a 10-pixel space between all the borders:

<style>
table {
    border-spacing: 15px;
}
table, th, td {
    border: 3px solid blue;
}
th, td {
    padding: 15px;
}
</style>

Setting Table Width and Height

By default, a table will render to be wide and tall enough to hold its content. However, you can use the CSS width and height properties to specify fixed dimensions for the table and its cells

In the example below, the table's width is set to 100% and the table header cells height is set to 40px:

<style>
table {
    width: 70%;        
    border-collapse: collapse;
}
th, td {
    padding: 10px;
    border: 5px solid orange;
}
th {
    height: 45px;
    text-align: center;
}
</style>

Controlling the Table Layout

To govern the layout of a table and ensure a fixed width, you can use the CSS table-layout attribute. This property specifies the layout algorithm for table cells, rows, and columns. This attribute has two possible values:

  • auto - Uses a table layout method that is automatically generated. The widths of the table and its cells are changed to match the content using this technique. This is the default value.
  • fixed - Sets the table layout algorithm to fixed. The horizontal arrangement of the table is determined by the table's width, the width of the columns, and the borders or cell spacing, rather than the contents of the cells. In most cases, it is faster than auto.

The HTML table in the following example is built up using the fixed layout method and has a fixed width of 300 pixels, according to the style requirements. Let's put it to the test and see how it goes:

<style>             
table {
    width: 250px;
    border-collapse: separate;            
}
table, tr, th, td{
    border: 2px solid blue;
}
.auto {
    table-layout: auto;
}
.fixed {
    table-layout: fixed;
}
td{
    width: 40%;
}
</style>

Tip: You may improve the table rendering efficiency by setting the table-layout attribute to a fixed value. This property's fixed value allows the table to be presented one row at a time, presenting users with information more quickly.

Note that on big tables with a fixed value for the table-layout attribute, users will not view any section of the table until the browser has displayed the entire table.


Aligning the Text Inside Table Cells

Text content inside table cells can be aligned horizontally or vertically.

Horizontal Alignment of Cell Contents

You can align the text inside table cells horizontally using the CSS text-align property. The text can be aligned to the left, right, center, or justified.

<style>
table {
    width: 100%;        
    border-collapse: collapse;
}
th, td {
    padding: 10px;
    border: 2px solid orange;
}
th {
    text-align: center;
}
</style>

Vertical Alignment of Cell Contents

Similarly, you can use the CSS vertical-align property to align the content inside "th" and "td" elements vertically.

The vertical alignment is set to center by default. In the example below, the text inside "th" components is vertically bottom-aligned:

<style>
table {
    width: 100%;        
    border-collapse: collapse;
}
th, td {
    padding: 10px;
    border: 3px solid orange;
}
th {
    height: 40px;
    vertical-align: bottom;
}
</style>
    

Controlling the Position of Table Caption

The CSS caption-side property controls the vertical position of a table caption. You can place the caption at the top or bottom of the table.

<style>
table, td, th {
    border: 2px solid purple;
}
caption {
	caption-side: bottom;
}
</style>

Note: Internet Explorer 8 supports the caption-side property only if a !DOCTYPE is specified.


Handling Empty Cells

The CSS empty-cells property manages the display of cells with no visible content in tables that use the separate border model.

The default value is show which displays empty cells with regular borders and backgrounds. If set to hide no borders or backgrounds are displayed around the empty cells. Here's an example:

<style>
table {
    width: 300px;
    border-collapse: separate;
}
table, th, td{
    border: 3px solid purple;
}
table.empty-show {
    empty-cells: show;                        
}
table.empty-hide {
    empty-cells: hide;           
}        
</style>

Note: A non-breaking space ( ) within a table cell prevents it from being empty. As a result, the hide value will not conceal the borders and backgrounds even if the cell seems to be empty.


Creating Zebra-striped Tables

Creating zebra-striped tables, where alternating rows have different background colors, can improve readability, especially for tables with a lot of data.

This effect can be achieved using the CSS :nth-child() pseudo-class selector. The following style rules highlight every odd row within the table body:

<style>
table {
    width: 100%;        
    font-family: arial, sans-serif;
    border-collapse: collapse;
}
th, td {
    padding: 10px;
    text-align: left;
    border-top: 5px solid orange;
}
tbody tr:nth-child(odd) {
    background-color: purple;
}
</style>

Note that the :nth-child() pseudo-class selects components depending on their siblings order. As an input, it can accept a number, the keyword even or odd, or an expression of the type xn+y where x and y are integers (e.g. 1n, 2n, 2n+1,...).


Making a Table Responsive

To make a table responsive, allowing horizontal scrolling on smaller screens to support mobile devices, you can enclose the table within a div element and apply the CSS overflow-x: auto style. Here's an example:

<style>
table {
    width: 100%;
    border-collapse: collapse;
}
th, td {
    padding: 10px;
    text-align: center;
    border: 5px solid purple;
    white-space: nowrap; /* to prevent text wrapping */
}
.responsive-table {
    overflow-x: auto;
}
</style>

FAQ

How can you make a CSS table responsive?

To make a CSS table responsive, you can use the following techniques:

  • Media Queries: Define different CSS styles for different screen sizes using media queries. Adjust the table's layout, font sizes, and other properties to ensure readability on smaller screens.
  • Flexbox or Grid: Convert the CSS table layout into a flexible box (display: flex) or a grid (display: grid) layout. This allows the table to adapt to different screen sizes more easily.
  • Scrollable Containers: Wrap the table in a container with overflow-x: auto to enable horizontal scrolling on smaller screens. This prevents the table from becoming too narrow to read.

How can you apply alternating row colors to a CSS table?

To apply alternating row colors to a CSS table, you can use the :nth-child() pseudo-class to target even and odd rows and apply different background colors. For example:

tr:nth-child(even) {
    background-color: lightgray;
}

tr:nth-child(odd) {
    background-color: white;
}

This will give the table a striped appearance, making it easier for users to distinguish between rows.

How can you center-align the content within a table cell using CSS?

To center-align the content within a table cell using CSS, you can use the text-align property on the cell's CSS selector. For example:

td {
    text-align: center;
}

How can you set a fixed width for a table column in CSS?

To set a fixed width for a table column in CSS, you can use the width property on the <col> element that corresponds to the column you want to style. For example:

col:nth-child(2) {
    width: 150px;
}

This will set a fixed width of 150 pixels for the second column in the table.

How can you apply a border to a table cell only when the user hovers over it using CSS?

To apply a border to a table cell only when the user hovers over it, you can use the :hover pseudo-class along with the CSS border property. For example:

td:hover {
    border: 2px solid blue;
}

This will add a blue border to the table cell when the user hovers over it. You can adjust the border properties as needed for your design.

How can you apply a background color to a table row when a user selects it?

To apply a background color to a table row when a user selects it, you can use the :active pseudo-class along with the CSS background-color property:

tr:active {
    background-color: lightblue;
}

This will apply a light blue background color to the table row while the user is clicking on it.

How can you style the first and last cells in a table column using CSS?

You can style the first and last cells in a table column using the :first-child and :last-child pseudo-classes along with appropriate selectors:

/* Style the first cell in each column */
td:first-child {
    font-weight: bold;
}

/* Style the last cell in each column */
td:last-child {
    text-align: right;
}

These styles will be applied to the first and last cells in each column of the table.

How can you set a specific width for the entire table using CSS?

To set a specific width for the entire table using CSS, you can use the width property on the <table> element:

table {
    width: 100%; /* Set the desired width */
}

This will set the table's width to 100% of its containing element's width. You can adjust the value as needed.

What is the difference between the "border" and "outline" properties for table cells in CSS?

Both the border and outline properties are used to create visual boundaries around table cells, but there are key differences:

  • Border: The border property sets a border around the content of a table cell. It can have different styles, widths, and colors for each side of the border.
  • Outline: The outline property also creates a boundary around a table cell, but it doesn't affect the layout of the content. It's typically used for highlighting elements, and it doesn't have separate styles for each side.

How can you align text vertically within a table cell using CSS?

To vertically align text within a table cell using CSS, you can use the vertical-align property:

td {
    vertical-align: middle; /* Aligns text vertically at the center */
}

The vertical-align property has several values, such as top, middle, bottom, and baseline, that determine how the text aligns vertically within the cell.

How can you style a table row when a user hovers over it using CSS?

To style a table row when a user hovers over it, you can use the :hover pseudo-class on the <tr> element:

tr:hover {
    background-color: lightgray; /* Apply the desired style on hover */
    cursor: pointer; /* Change cursor to indicate interactivity */
}

This will change the background color of the table row to light gray when the user hovers over it. The cursor property is set to "pointer" to indicate that the row is interactive.

How can you apply a gradient background to a table cell using CSS?

To apply a gradient background to a table cell using CSS, you can use the background-image property along with the linear-gradient() function:

td {
    background-image: linear-gradient(to bottom, #ffcc00, #ff9900);
    color: white; /* Set text color to ensure readability */
}

In this example, a gradient from #ffcc00 to #ff9900 is applied vertically to the cell background. The color property is set to white to ensure the text remains readable.

How can you set the width and height of a table cell using CSS?

You can set the width and height of a table cell using the width and height properties:

td {
    width: 100px; /* Set the desired width */
    height: 50px; /* Set the desired height */
}

This will set the width of each cell to 100 pixels and the height to 50 pixels. Adjust the values to meet your design requirements.

How can you add space between the table cells using CSS?

To add space between the table cells using CSS, you can use the border-spacing property on the <table> element:

table {
    border-spacing: 10px; /* Set the desired spacing value */
}

This property controls the spacing between adjacent cells in the table. Adjust the value to achieve the desired amount of space.

How can you style a table caption using CSS?

To style a table caption using CSS, you can use the caption-side property to adjust its placement and apply styles directly to the <caption> element:

caption {
    caption-side: bottom; /* Adjust the caption placement */
    font-size: 18px; /* Set the desired font size */
    color: #333; /* Set the desired text color */
}

This will set the caption at the bottom of the table and style its font size and color. Adjust the styles to match your design preferences.

How can you create a zebra-striped effect using CSS for table rows?

To create a zebra-striped effect using CSS for table rows, you can use the :nth-child() pseudo-class to target even and odd rows and apply different background colors:

/* Apply styles to even rows */
tr:nth-child(even) {
    background-color: #f2f2f2;
}

/* Apply styles to odd rows */
tr:nth-child(odd) {
    background-color: #ffffff;
}

This will give your table a zebra-striped appearance with alternating background colors for even and odd rows.

How can you make a table responsive using CSS for smaller screen sizes?

To make a table responsive for smaller screen sizes using CSS, you can utilize media queries and adjust the table layout. For example, you can convert the table cells into block elements for smaller screens:

@media (max-width: 768px) {
    td {
        display: block;
        width: 100%; /* Set cell width to full width of container */
    }
}

This media query will change the table cells to stack vertically on screens with a maximum width of 768px, making the table more readable on smaller devices.

How can you make the text within a table cell wrap to multiple lines if it's too long using CSS?

To make the text within a table cell wrap to multiple lines if it's too long, you can use the word-wrap or overflow-wrap property along with white-space: normal:

td {
    white-space: normal;
    word-wrap: break-word; /* For legacy browsers */
    overflow-wrap: break-word; /* For modern browsers */
}

These properties ensure that long words or strings will wrap and break to fit within the cell's width.

How can you add a background image to a table cell using CSS?

To add a background image to a table cell using CSS, you can use the background-image property:

td {
    background-image: url('image.jpg'); /* Set the image URL */
    background-size: cover; /* Adjust image sizing */
    background-repeat: no-repeat; /* Prevent image repetition */
}

This will set the specified image as the background of the table cell. You can adjust properties like background-size and background-repeat to control the image display.

How can you style the table header cells differently from the regular cells using CSS?

To style the table header cells differently from the regular cells using CSS, you can use the th element selector for header cells:

th {
    background-color: #333;
    color: white;
    font-weight: bold;
}

This example sets a different background color, text color, and font weight for the header cells compared to the regular td cells.

How can you make a table header sticky at the top of the page as the user scrolls using CSS?

To make a table header sticky at the top of the page as the user scrolls, you can use the position: sticky property on the th elements within the thead:

thead th {
    position: sticky;
    top: 0;
    background-color: #f0f0f0;
}

This will keep the header cells sticky at the top of the table container when the user scrolls. You might need to set a specific height for the table's thead element for this to work as intended.


Conclusion

CSS tables offer a powerful way to present tabular data on web pages with enhanced control over styling and layout. By applying CSS to tables, you can customize various aspects such as borders, backgrounds, spacing, and alignment. This allows you to create visually appealing and organized tables that are easy to read and navigate. CSS also enables responsive design for tables, making them adapt to different screen sizes and ensuring a seamless user experience across devices. Furthermore, CSS provides the flexibility to style individual table cells and rows, allowing for highlighting, color-coding, and other visual enhancements.

The guide explores specific CSS styling methods, including aligning text horizontally and vertically within cells, controlling table captions, and handling empty cells. The guide also delves into advanced techniques such as zebra-striping, contributing to the finesse of table presentation and improving readability. These strategies collectively transform tables into dynamic elements that not only logically convey information but also elevate the overall user interface.

Emphasizing the importance of responsiveness in table design, the guide introduces techniques for making tables responsive and adjusting layouts for various screen sizes. The exploration of topics such as collapsing table borders, horizontal and vertical alignment of cell contents, and controlling the position of table captions further enhances the developer's ability to create sophisticated and responsive table designs.

By leveraging CSS tables effectively, you can present data in a structured and visually engaging manner, improving the overall usability and readability of your web pages.