How to Add CSS Styling to An Element When Clicking It
--
New to CSS? Not sure how to add styles when clicking on an element?
Luckily, it’s pretty easy to do 😄 Here’s how it’s done:
Let’s Make a New Button 🕹️
<button class="button">Click Me!</button>
Let’s add a few default styles to the button:
.button {
font-size:20px;
background-color:red;
border:none;
color:#fff;
}
You’re Link Should Now Look Like This: (Click “Run Pen”)
You may notice that when you click on the button, there’s a thin blue border that forms around the button. Naturally, you may want another style when the button is clicked upon. Therefore, we can add the following CSS styles:
.button:active {
background-color:white;
color:red;
}
There it is: all you need to change the styles when clicking on a CSS element is a “active” selector on your chosen CSS element.
See for yourself in the Code Pen below:
Want to change styles on an image or div? There’s no difference!
All you need is an “:active” CSS selector:
.image:active {
opacity:0.9;
}.container:active {
border-color:blue;
}
That’s All Folks!
And that’s how you can adjust CSS styles on click!
If you enjoyed this tutorial and would like to see more, make sure to give this story a clap 👏!
If you really enjoyed this tutorial, consider buying me a cup of coffee! ☕