Search code examples
htmlcssrazorhtml-helper

Custom styled radio buttons using ASP.NET MVC Helpers


I am struggling to style Html.RadioButtonFor() form elements in my ASP.NET MVC project. I'm trying to replicate something like this: http://jsfiddle.net/YB8UW/2374/

But with my HTML form section that looks like this:

<div class="form-group">
    <label>@Html.RadioButtonFor(m => m.Presave.IsTrack, true) Track</label>
    <label>@Html.RadioButtonFor(m => m.Presave.IsTrack, false) Album</label>
</div>

None of my styles are picked up when I do stuff like:

input[type="radio"]:checked + label {
    background:yellow;
}

The css for the label outline (taken from the fiddle) in my project works fine though

label {
    padding: 5px;
    border: 1px solid #CCC;
    cursor: pointer;
    z-index: 90;
}

but that's about it, I cannot get the background color style for the selected element. What additional syntax do I have to add for this to be picked up?

Thanks!


Solution

  • The + selector is looking for the label right after a checked radio and the following:

    <div class="form-group">
        <label>@Html.RadioButtonFor(m => m.Presave.IsTrack, true) Track</label>
        <label>@Html.RadioButtonFor(m => m.Presave.IsTrack, false) Album</label>
    </div>
    

    will generate radio buttons that are inside labels e.g.

    <div class="form-group">
        <label><input type="radio" />...</label>
        <label><input type="radio" />...</label>
    </div>
    

    Putting the labels right after the @RadioButtonFor should do the trick:

    <div class="form-group">
        @Html.RadioButtonFor(m => m.Presave.IsTrack, true, new { id = "track" })
        <label for="track">Track</label>
        @Html.RadioButtonFor(m => m.Presave.IsTrack, false, new { id = "album" }) 
        <label for="album">Album</label>
    </div>