Home Styling @Html.CheckBoxFor as a slider
Reply: 1

Styling @Html.CheckBoxFor as a slider

kanpeki Published in 2017-09-14 11:19:01Z

I'm having trouble styling a checkbox generated by @Html.CheckBoxFor() as a slider.

I've identified the "culprit" to be the hidden input field. I've made a fiddle to illustrate the problem. It contains 3 checkboxes - one generated by @Html.CheckBoxFor(), the second one using the code generated by @Html.CheckBoxFor() with the hidden input commented out and the third classic checkbox.

You will see the slider is not working for the first one. I do need to use @Html.CheckBoxFor() because I want the checkbox to be bound to a property on my model, but can't figure out how to make the slider styling work...

In my view I have:

<div class="slider">
    @Html.CheckBoxFor(m => m.IsChecked, new { @class = "toggle-pill" })
    @Html.LabelFor(m => m.IsChecked, new { @class = "toggle-label" })

The .css for styling it:

.slider [type="checkbox"] {
    display: none;

.slider .toggle-label {
    display: block;
    width: 40px;
    height: 20px;
    position: relative;
    background: #ed495c;
    border-radius: 10px;
    transition: background 0.2s ease;
    cursor: pointer;

.slider .toggle-label::before {
    content: '';
    display: block;
    width: 50%;
    height: 100%;
    background: #ffffff;
    border-radius: 50%;
    box-shadow: 0 0 0 1px #d1d1d1;
    position: absolute;
    left: 0;
    top: 0;
    transition: transform 0.2s ease-in-out;

.slider [type="checkbox"]:checked + .toggle-label {
    background: #93ed49;

.slider [type="checkbox"]:checked + .toggle-label::before {
    -webkit-transform: translateX(100%);
    transform: translateX(100%);

The model property, IsChecked, is typeof bool.

Stephen Muecke
Stephen Muecke Reply to 2017-09-14 12:04:16Z

The issue is that your css for .slider [type="checkbox"]:checked + .toggle-label { and .slider [type="checkbox"]:checked + .toggle-label::before { use the adjacent sibling combinator (+) which selects the next sibling.

Because CheckboxFor() generates a <input type="hidden" .. /> immediately after the <input type="checkbox" .. />, the selector is choosing the wrong element (the hidden input, not the label).

You need to modify the css to use the general sibling combinator (~), so that your css becomes

.slider [type="checkbox"]:checked ~ .toggle-label {
    background: #93ed49;

.slider [type="checkbox"]:checked ~ .toggle-label::before {
    -webkit-transform: translateX(100%);
    transform: translateX(100%);

I assume your using a plugin for this, so you can either modify the original file, or add an additional css file containing the above.

Refer this forked fiddle to see how it works.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.369463 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO