Is there an option to have a checkbox without any labels / a container for the checkbox

I am sure some of you know of the next trick in CSS:

We have something we wanna do if we click a button and that’s possible to do with CSS alone using the checkbox:checked!

For example:

When using dash we have a problem, for the trick to work we need the checkbox to be on the same level as the element it affects if it’s checked.
and we can’t achieve it using
html.Input / dcc.checklist / dcc.input / dbc.checkbox / dmc.checkbox
Some of them just don’t let u use the checklist (inputs) and the others always have the checkbox inside a div or other elements.

Do you guys know a way around this?

hi, @jinnyzor wanted to ask if you know a way to accomplish this.
it’s so useful for web development and I just can’t find a way to do it in dash.

Hello @Matan,

Thanks for mentioning this, it is really nice to only need to use css sometimes. :+1:

Let’s see if this works for you with css:


.control-me::after {
    content: "😃";
    font-size: 100px;
}

.form-check:has(#toggle:checked) ~ .control-me::after {
    content: "😩";
}

label {
    background: #A5D6A7;
    padding: 0.5rem 1rem;
    border-radius: 0.5rem;
}

#toggle {
    position: absolute;
    height: 0;
    width: 0;

    /* Note, you may want to position the checkbox over top the label and set the opacity to zero instead. It can be better for accessibilty on some touch devices for discoverability. */
}

body {
    height: 100vh;
    margin: 0;
    display: grid;
    place-items: center;
    text-align: center;
    font: 900 24px/1.4 -system-ui, sans-serif;
}

app.py

import dash
from dash import Dash, html, dcc
import dash_bootstrap_components as dbc

app = Dash(__name__)

app.layout = html.Div([dbc.Checkbox(id='toggle', label='toggle'), html.Div(className='control-me')])

app.run(debug=True)

I believe this works. The reason, we had to use the parent to link to the control me class, but we needed to query inside of the parent to make sure that the value we wanted had changed.

:slight_smile:

Now that we know this, I’m sure the other ones can be figured out as well.

1 Like

As always @jinnyzor to the rescue! It works like a charm,

I will add a few notes for people that are going to use this:

  1. Make sure the checkbox component comes before whatever component you want it to affect otherwise it won’t work!
    the ~ the General Sibling Selector selects all next siblings, not the one that appears before it.
  2. you don’t have to use id you can use
.form-check:has(.form-check-input:checked) ~ .control-me::after {
    content: "😩";
}

immensely helpful when you’re building a multi-use component.

2 Likes