CSS selector - Doing something wrong

2019-07-15 14:23发布

问题:

I am trying to finalize a hide/show radio button option but I am stack with the CSS.

<input type=radio id="show" name="group">
<input type=radio id="hide" name="group" checked>
    <label id="id1" for="show"><span id="id1">show</span></label>
    <label id="id2" for="hide"><span id="id2">hide</span></label> 
    <br /><span>sdsahsahasa<br />
    asasfasfasfa<br />
    sfafsa<br />
    fsa<br />
    fsafsas</span><br />
<span id="content">Content</span>
    <table>
        <tr><td><span id="content">Content</span></td></tr>
    </table>

I am trying to find a way to show all the "content" id hidden text but it seems that when it is under that table it won't show up. Any ideas/suggestions? Here is the CSS I am currently using.

input {
display:none;
}

span#content {
    display:none;
}

input#show:checked ~ span#content{
  display:block;
}

input#show:checked ~ label#id1{
  display:none;
}
input#show:checked ~ label#id2{
  display:block;
}

input#hide:checked ~ label#id2{
  display:none;
}
input#hide:checked ~ label#id1{
  display:block;
}
input#hide:checked ~ span#content{
    display:none;
}

Live Demo: http://jsfiddle.net/LZ8Sc/

Thank you!

回答1:

You are relatively limited when using the :checked method. You are relying on the adjacent and general sibling combinators, +, ~. In this instance, if the element isn't a general preceding sibling, it isn't going to work. CSS is cascade; you would have to use JS if you want to be able to traverse the DOM or select elements that aren't siblings.

You do; however, have one option, which is to place the label elements at the root of the document, as you did, and then select the sibling elements's children. For instance:

input#show:checked ~ table tr td span#content,
input#show:checked ~ span#content {
  display:block;
}

EXAMPLE HERE

It's worth noting that an id MUST be unique. In your example, there are duplicate id's.