How to Create a Full-Width Table using CSS?
Creating a full-width table using CSS involves setting the table’s width to 100% and adjusting other relevant properties to ensure that it stretches across the entire width of its parent container. In this article, we will explain the approach to creating a full-width table using CSS.
Approach
- Create a container using <div> to hold a table.
- Inside the container, add a <table> element with appropriate <thead>, <tbody>, <tr>, <th>, and <td> elements for table headers and data.
- Reset the default margin and padding of the body and HTML elements to zero.
- Set the width of the body and html elements to 100% to ensure they take the full width of the viewport.
- Set the width of the table element to 100% to ensure it spans the full width of its container.
Example: The below code demonstrates the implementation to create a full-width table.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>Full Width Table</title>
<style>
body, html {
margin: 0;
padding: 0;
width: 100%;
}
.container {
width: 100%;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #000;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<div class="container">
<table>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data</td>
<td>Data</td>
<td>Data</td>
</tr>
<tr>
<td>Data</td>
<td>Data</td>
<td>Data</td>
</tr>
<tr>
<td>Data</td>
<td>Data</td>
<td>Data</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Output:
Contact Us