CSS for Checkbox and Radio should use general sibling selector rather than adjacent sibling selector
I use ASP.NET MVC to create my web sites, and I recent had an issue when applying your (normally awesome) CSS. Because the built-in MVC helpers add a second, hidden field after a checkbox, the adjacent sibling selector does not match, thus making selection problematic. For example, this selector:
.input-control.checkbox input[type="checkbox"]:checked + .helper:after
does not match the ,helper span in the following HTML:
<div class="input-control checkbox">
<input type="checkbox" name="helper" checked="checked" />
<input type="hidden" name="helper" value="false"/>
<span class="helper"></span>
</div>
I solved it by using the general sibling selector instead:
.input-control.checkbox input[type="checkbox"]:checked ~ .helper:after
Since the general sibling selector will work in both cases, I think it is more appropriate. Thanks and keep up the good work.
This is obvious, because the selector '+' look for the next element after base. So, the css
.input-control.checkbox input[type="checkbox"]:checked + .helper:after
Will look for the first element after the checked checkbox, that's
<input type="hidden" name="helper" value="false"/>
To have working with the selector '+', you should use move the helper up, like this
<div class="input-control checkbox">
<input type="checkbox" name="helper" checked="checked" />
<span class="helper"></span>
<input type="hidden" name="helper" value="false"/>
</div>
The problem in this case is that ASP.Net MVC renders two inputs (one after other) . Explanation for this behavior is here: http://stackoverflow.com/a/2697311
I also struggle with this issue and I see two possible solutions:
- use '~' instead of '+'
- use extra selector to match hidden input in-between similar to this
.input[type=checkbox] + .helper, .input[type=checkbox] + input[type="hidden"]+ .helper { .... }
Yes, I know it. I was thinking that ASP.Net can read the hidden input also if there is another element between.
Unfortunately code you (actually I) have is
<label class="input-control switch">
@Html.CheckBoxFor(m => m.IsAutoRestartEnabled)
<span class="helper"></span>
</label>
so I cannot control how it's rendered
changed + to ~