3

Below is my CSS and HTML code.

Given CSS selector is not applied when there is a hidden field between INPUT and SPAN tags

CSS

input[type="checkbox"] + .lbl:before {
    background-color: #FAFAFA;
    border: 1px solid #CCCCCC;
}

CSS Working

<label>
<input name="SMS" type="checkbox" />
<span class="lbl"> choice 2</span>
</label>

CSS Not Applied

<label>
<input name="SMS" type="checkbox" />
<input type="hidden" value="false" name="SMS">
<span class="lbl"> choice 2</span>
</label>

How can I change/add new CSS selector change to support both cases?

Note: The Hidden field was automatically generated by ASP.Net MVC framework and we dont have a control to place it in other place

3 Answers 3

3

The + indicates that the element is placed immediately after the checkbox.

You could change it to > which indicates a parent.

input[type="checkbox"] > .lbl:before {
    background-color: #FAFAFA;
    border: 1px solid #CCCCCC;
}

http://jsfiddle.net/TkamX/

Note: I have added a new div and used that as the parent element.

div > .lbl {
    background-color: #FAFAFA;
    border: 1px solid #CCCCCC;
}

You can also use a single selector by giving your span an ID and then select based on that.

Sign up to request clarification or add additional context in comments.

1 Comment

@Adrift - yes that's why I put it as a div in my example. I was going to state that having a span inside an input is bad practice etc. You can also use other selectors or an ID.
1

You can use the general sibling combinator ~ if you're trying to style a sibling that is not necessarily immediately following another element.

So in your case

input[type="checkbox"] ~ .lbl:before {
    background-color: #FAFAFA;
    border: 1px solid #CCCCCC;
}

Would work in both scenarios

http://jsfiddle.net/Hx8ZG/

Comments

1

If the only possible issue here is a hidden input field between the checkbox and the span, then you should be able to reference that in your selector:

input[type="checkbox"] + input[type="hidden"] + .lbl:before {
    ....
}

Alternatively, if the hidden field may or may not be there, then you'll need to allow for both options:

input[type="checkbox"] + .lbl:before, input[type="checkbox"] + input[type="hidden"] + .lbl:before {
    ....
}

If there could be more elements between the two, and you don't know what they could be, then you'll need to swap your + selector for a ~ selector, which selects any sibling rather than the adjacent one.

input[type="checkbox"] ~ .lbl:before {
    ....
}

This option might be the simplest, but does have the caveat that it might select things which wouldn't have been selected by your original + selector.

Hope that helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.