CSS Tables

CSS tables refer to the way CSS (Cascading Style Sheets) is used to style HTML tables. HTML tables are used to display tabular data, and CSS can be applied to control their layout, appearance, and responsiveness. CSS allows for detailed customization of table elements, including borders, padding, text alignment, colors, and more.

Basic HTML Table Structure

HTML tables are created using the <table>, <tr>, <th>, and <td> elements. Here is a simple example of an HTML table:


<table>
    <thead>
        <tr>
            <th>Header 1</th>
            <th>Header 2</th>
            <th>Header 3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Data 1</td>
            <td>Data 2</td>
            <td>Data 3</td>
        </tr>
        <tr>
            <td>Data 4</td>
            <td>Data 5</td>
            <td>Data 6</td>
        </tr>
    </tbody>
</table>

Basic CSS Table Properties

CSS can be applied to tables using a variety of properties to enhance their appearance and usability.

Table Borders

You can add borders to tables, table rows, table headers, and table cells:


table {
    border-collapse: collapse; /* Merge adjacent borders into a single border */
    width: 100%; /* Make the table take up 100% of the container width */
}

th, td {
    border: 1px solid black; /* Add a 1px solid black border to headers and cells */
    padding: 8px; /* Add padding inside headers and cells */
    text-align: left; /* Left-align text in headers and cells */
}

Table Header and Row Background Colors

You can style the table headers and rows with background colors for better readability:


th {
    background-color: #f2f2f2; /* Light grey background for headers */
}

tr:nth-child(even) {
    background-color: #f9f9f9; /* Light grey background for even rows */
}

tr:hover {
    background-color: #d1e7dd; /* Light green background on hover */
}

Text Alignment and Padding

You can control the alignment of text and the padding inside the cells:


th, td {
    text-align: center; /* Center-align text in headers and cells */
    padding: 10px; /* Add padding inside headers and cells */
}

CSS Tables – Interview Questions

Q 1: How are tables styled using CSS?
Ans: By applying CSS to table, tr, th, and td.
Q 2: What is border-collapse?
Ans: It merges table borders into a single border.
Q 3: How to add spacing between table cells?
Ans: Using border-spacing.
Q 4: What is table-layout?
Ans: It controls how table width is calculated.
Q 5: How to center a table?
Ans: Using margin: auto.

CSS Tables – Objective Questions (MCQs)

Q1. Which property is used to collapse table borders?






Q2. Which property controls spacing between table cells?






Q3. Which property aligns text inside table cells?






Q4. Which property sets background color of table rows?






Q5. Which HTML tag is styled using CSS tables?






Related CSS Tables Topics