6

Is is possible to toggle a class with only css?

Say I have the following:

<div class="parent">
   <div class="child collapsed">
        Boring Text
   </div>
</div>

Is is possible, just with css, that when you click on the parent, you can switch the collapsed class to expanded and vice versa?

KingKongFrog
  • 13,946
  • 21
  • 75
  • 124
  • As mentioned its a **No**. But it maybe worth looking at the checkbox hack: http://css-tricks.com/the-checkbox-hack/ if your really don't want to use js / jquery. Again its a hack, but does the job – mikedidthis Aug 14 '13 at 18:52

2 Answers2

11

Is is possible to toggle a class with only css?

No.

You can have state handled by using pseudo-classes such as :hover, :active, :checked, and :target but this is not the same as changing the state of class attributes the DOM.

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • @Wes, that is entirely unrelated to the question being asked. – zzzzBov Aug 14 '13 at 17:23
  • actually it is, since the mechanism is the same `.parent:active, !.parent *:active {}` –  Aug 14 '13 at 17:28
  • @Wes, no the question was about toggling a class, not about managing the state of a pseudo class. – zzzzBov Aug 14 '13 at 17:30
  • 3
    I don't understand why you are being so aggressive since it's glaring that OP was asking for a method to toggle between active/not active and not toggling a .class specifically. Also, mine was a note, I didn't say you are wrong. –  Aug 14 '13 at 17:40
  • @Wes, I thought OP was very explicit when he said "Is is possible, just with css, that when you click on the parent, you can switch the collapsed class to expanded and vice versa?" I'm not trying to be aggressive, I'm trying to be correct. If I'm wrong, please let me know where so that I can fix it. – zzzzBov Aug 14 '13 at 18:09
  • Looking at the OP's initial question the answer is no. However, being the helpful community we are, maybe we could look at the code provided and suggest a CSS only solution that has the same outcome, pseudo-classes, etc. – mikedidthis Aug 14 '13 at 18:24
  • @mikedidthis, feel free to add your own answer to the question. I only briefly touched on pseudo classes handling state, but if you feel it's worth elaborating on, by all means go ahead. – zzzzBov Aug 14 '13 at 18:29
  • @zzzzBov I will add a comment about the checkbox hack, which is probably as close as the OP is going to get with HTML / CSS alone. – mikedidthis Aug 14 '13 at 18:49
  • you can use checkbox hacks for [everything...](http://codepen.io/rlemon/pen/vmIlC) – rlemon Aug 14 '13 at 19:40
0

You can figure out some like this https://stackoverflow.com/a/76489732/8382657

.caret {
  transition: 0.5s;
}
.caret:not(.collapsed){
  transform: rotate(180deg);
}
.caret:is(.collapsed) {
  transform: rotate(0deg);
}
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129