I want to change the background color of a div when I click on it using only css not JavaScript. So when I click on it it should turn red. How do I do that using css?
I want to change the background color of a div when I click on it using only css not JavaScript. So when I click on it it should turn red. How do I do that using css?
2
Answers
You could use a checkbox inside that div to handle the click state and use
:has()
pseudo-class to change the style of the div.However, right now, the support for
:has()
is only at 92.79%. So alternatively, the checkbox could be before thediv
and use a position absolute to cover the div. Then you can to the same thing with the sibling selector:Let me clarify your doubt about how to change the background color of a div when you click on it with a simple example and easy-to-follow steps:
Step 1: Basic HTML Structure
First, we’ll start with a basic HTML structure. Create an HTML file (e.g., index.html) and add the following code:
In this code, we have a div with the class color-box and an initial background color of light blue. The text inside the div says "Click me!".
Step 2: Adding JavaScript
Next, we’ll add JavaScript to handle the click event and change the background color of the div. Create a JavaScript file (e.g., script.js) and add the following code:
In this JavaScript code:
We select the div by its ID using document.getElementById.
We define a function changeColor that generates a random color and sets it as the background color of the div.
We add an event listener to the div so that when it is clicked, the changeColor function is called.
Step 3: Putting It All Together
Now, when you open the index.html file in your web browser, you will see the div with the text "Click me!" in the center of the page. When you click on the div, its background color will change to a random color.
Hope you got it.✌