How to use pseudo-elements In CSS
In this method, pseudo-elements (:before or :after) are employed to visually simulate the addition of rows or columns upon hovering over the grid container. By styling the pseudo-element to represent a new row or column, the layout appears to expand dynamically upon hover without altering the DOM structure.
Example: Illustration of Adding Rows and Columns on hover in CSS using pseudo-elements
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Hover Expand Rows and Columns
With pseudo-elements
</title>
<style>
.container {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-auto-rows: 100px;
gap: 10px;
}
.item {
position: relative;
background-color: #ccc;
border: 1px solid #999;
display: flex;
justify-content: center;
align-items: center;
transition: all 0.3s ease;
}
.item::before {
content: "";
position: absolute;
background-color: rgba(255, 0, 0, 0);
transition: all 0.3s ease;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
}
.item:hover::before {
background-color: rgba(255, 0, 0, 0.3);
}
.item:hover:nth-child(3n+2)::before {
width: 200%;
}
.item:hover:nth-child(3n+1)::before {
height: 200%;
}
</style>
</head>
<body>
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
</div>
</body>
</html>
Output:
How to Add Rows & Columns on hover in CSS ?
Adding rows and columns on hover in CSS allows you to dynamically expand a grid layout when a user hovers over it. This can be visually appealing and useful for displaying additional information or options.
We can use the below approaches to Add Rows and Columns on hover in CSS:
Table of Content
- Using JavaScript
- Using pseudo-elements
- Using Grid