Reputation: 401
I want to ask you a CSS question. My English is not good, but I try to express it completely! Today I hope to change the background to red after clicking, and not to have the hover effect (now hover will turn yellow in the past). If I don’t use javascript and jquery and only use CSS, how can I do it?
Thank you all for watching in advance, I really need your help!
ex
$('.button').on('click',function(){
$(this).toggleClass('red');
})
.button {
width: 100px;
height: 100px;
border: 1px solid #222;
text-align: center;
}
.button:hover {
background-color: yellow;
}
.red {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="button">123</div>
<div class="button">123</div>
Upvotes: 3
Views: 46
Reputation: 61
There's a CSS selector known :active
this part of CSS activates when any element is clicked. Read more about it on W3 Schools.
Upvotes: 1
Reputation: 337560
To achieve what you require you need to make the .red
selector more specific, so that it cannot be overridden by the :hover
state.
In this case you can achieve it by preceding it with .button
$('.button').on('click', function() {
$(this).toggleClass('red');
})
.button {
width: 100px;
height: 100px;
border: 1px solid #222;
text-align: center;
}
.button:hover {
background-color: yellow;
}
.button.red {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="button">123</div>
<div class="button">123</div>
One thing to note is that people often use, or are suggested to use, the !important
flag in cases like this, to override styles. However this is not a good approach as it means that the style which had the flag applied cannot as easily be overridden through specificity. As such maintenance and debugging can become much harder.
For more information on CSS selector specificity, see this answer on the subject.
Upvotes: 2