I'm currently developing a site that uses the :checked variable to apply rules to the CSS. I've got a checkbox input that when triggered, should accomplish two things. The first thing it should do is expand a div from a height of 0 to 200 when checked, and back to 0 when unchecked. I had no problems with triggering that first task. The second thing that should be accomplished upon checking the box, is a transform: rotate(45deg) of a div with a "+" in it that should rotate 45 degrees into an "x" (not an actual x, but a rotated +).
I've currently got my code setup to display the animation on :hover, but that's just for illustrative purposes, that wouldn't be in my final code. So hover over the "+ to see what I'm trying to accomplish with the :checked input.
If you're willing to take a look at my code, and tell me what I'm doing wrong, I'd be greatly appreciative! Let me know if you have any questions.
Note: Ideally I'm looking for a pure CSS solution without the need for JS. Let me know if this isn't possible.
Here's my code pen.
just add the class="checkbox" to your checkboxes. Then create that style in your css code.
A checkbox is an HTML element that takes input from the user. It is possible to style a checkbox using Pseudo Elements like :before, :after, hover and :checked.
The :checked pseudo-class in CSS selects elements when they are in the selected state. It is only associated with input ( <input> ) elements of type radio and checkbox . The :checked pseudo-class selector matches radio and checkbox input types when checked or toggled to an on state.
Yes, standard behaviour is the value is only sent if the checkbox is checked.
I wrote a similar solution the other day, here.
Basically, you are limited when using the :checked
method. You are relying on the adjacent and general sibling combinators, +
, ~
. If the element isn't a general preceding sibling, it isn't going to work.
In this example, .expand
was not a preceding sibling. Therefore the solution is to place the input
element at the root of the document, and then use the selector input[name='panel']:checked ~ label .rotate
to change the .rotate
element. Note, that the general sibling combinator, ~
is now also being used as opposed to the adjacent sibling combinator, +
.
No need for JS - UPDATED EXAMPLE
Modified HTML:
<input type="checkbox" name="panel" class="hidden" id="panel"/>
<label for="panel">
Click Me
<div class="rotate">+</div>
</label>
<div class="expand">
Content goes here.
</div>
Updated CSS:
input[name='panel']:checked ~ label .rotate {
transform: rotate(45deg);
-o-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-webkit-transform: rotate(45deg);
}
It's worth noting that I moved the transition properties to the .rotate
element too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With