thelolcat
thelolcat

Reputation: 11545

Select next element when input is checked

HTML:

<label>
  <input type="checkbox" />
</label>
<div>
  stuff
</div>

I'd like to be able to style the DIV element depending on the checked state of the input, like

input ~ div{
  display: none;
}

input:checked ~ div{
  display: block;
}

Obviously the~ selector doesn't seem to work here. Neither does +

Is there any other solution (besides javascript) ?

Upvotes: 2

Views: 4852

Answers (3)

Mohammad Al-Ani
Mohammad Al-Ani

Reputation: 576

if any one need extra solution

<input id="myCheckbox" type="checkbox" />
<label for="myCheckbox"> This is my label</label>

<div>
    show when check box is checked
</div>

and the css

#myCheckbox ~ label ~ div { display: none; }
#myCheckbox:checked ~ label ~ div { display: block; }

happy coding !!!

Upvotes: 2

Cam
Cam

Reputation: 1902

Try this, im not sure what its cross browser compatibility is.

input:checked + div
{
background: #333;
height: 30px;
width: 30px;
} 

This should work, but I wouldnt do it, I would do Javascript.

See my jsfiddle

Upvotes: 1

Maloric
Maloric

Reputation: 5615

Sadly there is no way to select an ancestor in pure CSS, which is what you would require to select an ancestor's sibling.

I have seen people surround other content with a label - while this is a very questionable practice, it would allow you to use the + selector to style the div:

<label>
    <input type="checkbox" />

    <div>
      stuff
    </div>
</label>

Edit:

Or this (thanks to @lnrbob for pointing it out)

<label for="myCheckbox">
    This is my label
</label>

<input id="myCheckbox" type="checkbox" />
<div>
    stuff
</div>

Upvotes: 0

Related Questions