Derek
Derek

Reputation: 8628

Pure CSS change styling of div element with checkbox

I'm trying to toggle the CSS of a sibling by using the checked state of a sibling checkbox.

Is it possible to target elements anywhere on the page from the checked pseudo class from a checkbox?

I'm trying to avoid using any javascript.

https://codepen.io/dyk3r5/pen/WOmxpV?editors=1111

html,
body {
  height: 100%;
}

.container {
  height: 100%;
  display: flex;
  justify-content: center;
}

label {
  color: #000;
  font-weight: 600;
  height: 25px;
  padding: 5px 10px;
  border-bottom: 2px solid lightgrey;
  margin: 5px 1px;
}

input[type="radio"] {
  display: none;
}

input[type="radio"]:checked + label {
  border-bottom: 2px solid red;
}

input[type="radio"]:checked > div p {
  display: none;
}
<div class="container">
  <div id="new-account">
    <input type="radio" id="opt1" name="radiolist" checked>
    <label for='opt1'>New Account</label>
    <div class="content">
      <p>Lorem Ipsum</p>
    </div>
  </div>

  <div id="existing-account">
    <input type="radio" id="opt2" name="radiolist">
    <label for='opt2'>Existing Account</label>
    <div class="content">
      <p>Lorem Ipsum 2</p>
    </div>
  </div>
</div>

Upvotes: 1

Views: 693

Answers (2)

norin89
norin89

Reputation: 482

Your mistake is in this line:

input[type="radio"]:checked > div p

your div element is not a "direct children" of input element. What you need here is "general sibling selector" to address any following div sibling.

So it should be:

input[type="radio"]:checked ~ div p

Upvotes: 1

ankita patel
ankita patel

Reputation: 4251

Use css like

input[type="radio"]:checked + label + .content p {
  display: none;
}  

Upvotes: 0

Related Questions