Black Lives Matter. Please consider donating to Black Girls Code today.

RadioItem css styling as Button Group

Hello,

This is both a (partial) answer & question.

I wanted to style my RadioItems as buttons – similarly to the dbc ButtonGroup, but without having to emulate the “only one selected” functionality through callbacks.

I have gotten that far:
image

With this python:

dcc.RadioItems(..., className='radiobutton-group')

and this CSS in ./assets/radio.css:

.radiobutton-group > label > input[type="radio"] {
    vertical-align: middle;
}
/* Hide if unchecked */
.radiobutton-group > label > input[type="radio"]:not(:checked) {
    position: absolute;
    left: -9999em;
    top: -9999em;
}
/* Buttons */
.radiobutton-group > label {
    padding: .25em .5em;
    cursor: pointer;
    border: 1px solid #28608f;
    margin-right: -1px;
    color: #fff;
    background-color: #428bca;
}
/* Rounded button corners */
.radiobutton-group > label:first-of-type {
      border-radius: .7em 0 0 .7em;
}
.radiobutton-group > label:last-of-type {
      border-radius: 0 .7em .7em 0;
} 

One thing is still missing to remove the ugly moving radio: How can I change the button color of the checked item?

This codepen is able to do it because the html structure is different. Dash embed the <input> in the <label>, so without a CSS parrent selector I don’t see a way:

<div id="the-dash-id" class="radiobutton-group">
    <label class="">
      <input class="" type="radio">
      15min
    </label>
    <label ...>...</label>
</div>

You could use dbc.RadioItems instead of dcc.RadioItems as the interface is the same, but the input and label are siblings of each other rather than having the input nested inside the label. It also has arguments labelClassName and labelCheckedClassName to make this kind of thing easier to achieve.

Here’s an example too showing how some custom CSS could be used to style the radios as buttons.

You can do all of that without linking Bootstrap styles if you don’t want them, if you don’t link a Bootstrap stylesheet then dbc.RadioItems just renders as plain HTML.

1 Like