In this tutorial, we will explore how to create tables using only DIV elements and CSS. This approach can be useful when you need to create a table-like structure without using the traditional TABLE element.
Introduction to Table-Like Structures with DIVs
To create a table-like structure with DIVs, we need to use CSS to define the layout and appearance of the elements. We will use the display
property to make the DIVs behave like table rows and cells.
Basic Structure
The basic structure of our table consists of a container DIV (.table
) that contains one or more row DIVs (.row
), which in turn contain one or more cell DIVs (.cell
). The HTML structure looks like this:
<div class="table">
<div class="row">
<div class="cell">Cell 1</div>
<div class="cell">Cell 2</div>
<div class="cell">Cell 3</div>
</div>
<div class="row">
<div class="cell">Cell 4</div>
<div class="cell">Cell 5</div>
<div class="cell">Cell 6</div>
</div>
</div>
CSS Styles
To make the DIVs behave like table rows and cells, we need to add the following CSS styles:
.table {
display: table;
width: 100%;
}
.row {
display: table-row;
}
.cell {
display: table-cell;
border: 1px solid #ddd;
padding: 10px;
}
These styles make the .table
DIV a block-level element that contains one or more .row
DIVs, which are displayed as table rows. The .cell
DIVs are displayed as table cells and have a border and padding to give them a table-like appearance.
Responsive Tables
To make our table responsive, we can add the following CSS styles:
.table {
display: table;
width: 100%;
table-layout: fixed;
}
.row {
display: table-row;
}
.cell {
display: table-cell;
border: 1px solid #ddd;
padding: 10px;
width: 33.33%; /* adjust the width to make the cells responsive */
}
These styles make the table responsive by setting the table-layout
property to fixed
and adjusting the width of the .cell
DIVs to a percentage value.
Grid-Based Approach
Alternatively, we can use CSS Grid to create a table-like structure. This approach is more elegant and flexible than using tables or DIVs with display: table-cell
. Here’s an example:
.table {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}
.cell {
border: 1px solid #ddd;
padding: 10px;
}
This code creates a grid container with three columns and a gap between the cells. The .cell
DIVs are displayed as grid items and have a border and padding to give them a table-like appearance.
Conclusion
In this tutorial, we learned how to create tables using only DIV elements and CSS. We explored different approaches, including using display: table-cell
and CSS Grid. By using these techniques, you can create responsive and flexible table-like structures that are easy to maintain and customize.