Click on div to change background color css
Click on the div to change the background color of the CSS
In web development, you often encounter scenarios where clicking an element triggers some interactive effect. Clicking a div
element to change its background color is a common requirement. This article will discuss in detail how to achieve this effect using CSS.
Method 1: Using the :active
Pseudo-Class
The :active
pseudo-class indicates the state of an element when it is activated by the user. In this state, we can change the element’s style, such as its background color. By utilizing the :active
pseudo-class, we can achieve the effect of changing the background color of a div
by clicking it.
div:active {
background-color: red;
}
In the above code, when the user clicks the div
element, its background color changes to red. This method has the advantage of being simple and direct, but the disadvantage is that the effect is only visible at the moment the user clicks; the background color returns to its original state after the mouse is released.
Method 2: Combining the :hover
and :active
Pseudo-Classes
To ensure that the background color of the div
element persists after clicking, we can combine the :hover
and :active
pseudo-classes.
div:hover {
background-color: blue;
}
div:active {
background-color: red;
}
In this code, when the mouse hovers over the div
, the background color changes to blue; when the user clicks the div
, the background color changes to red. This achieves the goal of changing the background color when clicking the div
and maintaining the effect.
Method 3: Using JavaScript
If you want the background color of the div
element to persist after clicking it, you can use JavaScript to achieve this. Here is a simple example code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change Background Color</title>
<style>
#myDiv {
width: 200px;
height: 200px;
background-color: blue;
cursor: pointer;
}
</style>
</head>
<body>
<div id="myDiv" onclick="changeColor()"></div>
<script>
function changeColor() {
var div = document.getElementById("myDiv");
div.style.backgroundColor = "red";
}
</script>
</body>
</html>
In this code, we use JavaScript to bind the onclick
event to the div
element. When the user clicks the div
, the event is triggered. The changeColor()
function changes the background color to red.
Summary
This article introduced three methods for changing the background color of a div
when it’s clicked: using the :active
pseudo-class, combining the :hover
and :active
pseudo-classes, and using JavaScript. Each method has its own advantages and disadvantages; choose the one that best suits your needs.