Botón on/off o switch en HTML y CSS | Programador Web Valencia

Botón on/off o switch en HTML y CSS

2 minutos

HTML5 y CSS3

Con la llegada de los dispositivos móviles se han hecho muy populares el uso de botones con dos opciones, también llamadas botones on/off o switch. Un elemento que nos proporciona 2 estados: encendido/apagado, abierto/cerrado, etc. No existe ninguna ayuda nativa dentro del estándar HTML, por lo que será necesario hacer un poco de magia con los input checkbox.

DEMO

Pulsa aquí 👉

HTML

El secreto radica en disponer de un checkbox oculto, para disponer del estado checked y un label que proporcionará la forma del botón.

<div class="switch-button">
    <!-- Checkbox -->
    <input type="checkbox" name="switch-button" id="switch-label" class="switch-button__checkbox">
    <!-- Botón -->
    <label for="switch-label" class="switch-button__label"></label>
</div>

CSS

Jugaremos con el before del label (o el botón) con el objetivo de crear el circulo blanco, mientras que al propio label lo usaremos para añadir nuestro color de fondo (rojo o verde).

Cuando sea pulsado el label automáticamente el checkbox cambiará a checked (pulsado), haciendo sencilla la tarea de cambiar su posición.

:root {
    --color-green: #00a878;
    --color-red: #fe5e41;
    --color-button: #fdffff;
    --color-black: #000;
}
.switch-button {
    display: inline-block;
}
.switch-button .switch-button__checkbox {
    display: none;
}
.switch-button .switch-button__label {
    background-color: var(--color-red);
    width: 5rem;
    height: 3rem;
    border-radius: 3rem;
    display: inline-block;
    position: relative;
}
.switch-button .switch-button__label:before {
    transition: .2s;
    display: block;
    position: absolute;
    width: 3rem;
    height: 3rem;
    background-color: var(--color-button);
    content: '';
    border-radius: 50%;
    box-shadow: inset 0px 0px 0px 1px var(--color-black);
}
.switch-button .switch-button__checkbox:checked + .switch-button__label {
    background-color: var(--color-green);
}
.switch-button .switch-button__checkbox:checked + .switch-button__label:before {
    transform: translateX(2rem);
}

Completo

Todo unido quedaría de la siguiente forma.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width" />
        <style type="text/css" media="screen">
            :root {
                --color-green: #00a878;
                --color-red: #fe5e41;
                --color-button: #fdffff;
                --color-black: #000;
            }
            .switch-button {
                display: inline-block;
            }
            .switch-button .switch-button__checkbox {
                display: none;
            }
            .switch-button .switch-button__label {
                background-color: var(--color-red);
                width: 5rem;
                height: 3rem;
                border-radius: 3rem;
                display: inline-block;
                position: relative;
            }
            .switch-button .switch-button__label:before {
                transition: .2s;
                display: block;
                position: absolute;
                width: 3rem;
                height: 3rem;
                background-color: var(--color-button);
                content: '';
                border-radius: 50%;
                box-shadow: inset 0px 0px 0px 1px var(--color-black);
            }
            .switch-button .switch-button__checkbox:checked + .switch-button__label {
                background-color: var(--color-green);
            }
            .switch-button .switch-button__checkbox:checked + .switch-button__label:before {
                transform: translateX(2rem);
            }
        </style>
    </head>
    <body>
        <div class="switch-button">
            <input type="checkbox" name="switch-button" id="switch-label" class="switch-button__checkbox">
            <label for="switch-label" class="switch-button__label"></label>
        </div>
    </body>
</html>

Si te ha gustado, por favor deja un comentario con tus impresiones. Y sino… pues también.

Esta obra está bajo una Licencia Creative Commons Atribución-NoComercial-SinDerivadas 4.0 Internacional.

Atribución/Reconocimiento-NoComercial-SinDerivados 4.0 Internacional

¿Me ayudas?

Comprame un café
Pulsa sobre la imagen

No te sientas obligado a realizar una donación, pero cada aportación mantiene el sitio en activo logrando que continúe existiendo y sea accesible para otras personas. Además me motiva a crear nuevo contenido.

Comentarios

{{ comments.length }} comentarios

Nuevo comentario

Nueva replica  {{ formatEllipsisAuthor(replyComment.author) }}

Acepto la política de Protección de Datos.

Escribe el primer comentario

Tal vez también te interese...