0

I currently have something like this

on jsfiddle

HTML:

.ln-header {
    cursor: pointer;
}

.ln-header::after {
    content: "+";
    margin-left: 10px;
    transition: 400ms;
}

.list-wrap {
    display: none;
}

.checkbox1:checked + .list-wrap {
    display: block;
}

.checkbox1:checked + .ln-header::after {
    transform: rotate(45deg);
}

.checkbox1:checked + .ln-wrap::after {
    transform: rotate(45deg);
}

.checkbox1 {
    display: none;
}
<div>
  <div>
    <label for="list1" class="localnav-categories-label">
      <span class="ln-header">categories</span>
    </label>
    <input type="checkbox" id="list1" class="checkbox1">
    <nav class="list-wrap">
      <ul>
        <li>
          <a href="#">one</a>
        </li>
        <li>
          <a href="#">two</a>
        </li>
      </ul>
    </nav>
  </div>
</div>

I'm trying to get the plus sign (as an ::after element) to rotate, preferably with an animation, while a list pops up. Currently, I am only able to get the list to appear, while the plus sign remains static. I've heard about the checkbox only affecting its sibling element (may be wrong), but after playing around with the location, where I have it now seems to be the only place that it'll work for the list to appear.

How could I make it so that when I check the checkbox, both the list appears and the '+' rotates simultaneously?

Thanks!

Kai
  • 27
  • 4

1 Answers1

1
  • First, you need to bring <input type="checkbox" id="list1" class="checkbox1"> to the front of anything you want to control the style of, since sibling selectors can only select forwards.

  • Second, you need to use ~ instead of + to select siblings that do not have to be right next to each other.

  • Third, you can't rotate an inline element(the default display of pseudo elements is inline), so you need to change the display of .ln-header::after to inline-block or inline-flex etc.

  • Finally, since .ln-header is a deeper element, you need to select it with a descendant selector .checkbox1:checked ~ * .ln-header::before

Then there you have it:

.ln-header {
    cursor: pointer;
}

.ln-header::after {
    content: "+";
    margin-left: 10px;
    transition: 400ms;
    display: inline-block;
}

.list-wrap {
    display: none;
}

.checkbox1:checked ~ .list-wrap {
    display: block;
}

.checkbox1:checked ~ * .ln-header::after {
    transform: rotate(45deg);
}

.checkbox1 {
    display: none;
}
<div>
  <div>
    <input type="checkbox" id="list1" class="checkbox1">
    <label for="list1" class="localnav-categories-label">
      <span class="ln-header">categories</span>
    </label>
    <nav class="list-wrap">
      <ul>
        <li>
          <a href="#">one</a>
        </li>
        <li>
          <a href="#">two</a>
        </li>
      </ul>
    </nav>
  </div>
</div>
Hao Wu
  • 17,573
  • 6
  • 28
  • 60