Search code examples
javascriptcssreactjsreact-bootstrap

Custom checkbox with label not fitting


I have tried to build my own checkbox which look like a buttom and find various solution but the design is still not good because the one of the element is not properly showing

As you can see on the image below, once the image is selected, the oragne background is not covering the entire button to looks good.

enter image description here

I try to fix it but most of the time, I am breaking the design

import React from 'react';
import './CheckboxButton.css';

class CheckboxButton extends React.Component {

    render(){
        return(
            <div id="ck-button">
                <label>
                    <input type="checkbox" value="1" hidden/><span>{this.props.text}</span>
                </label>
            </div>
        )
    }
}
export default CheckboxButton;

the css is :


 
 #ck-button {
     margin:3px;
     background-color: transparent;
     overflow:auto;
     float:left;
     box-shadow: 0px 8px 18px 0 rgba(0,0,0,0.14);
     border-radius: 21px;
     border: solid 2px #ff7255;

 }
 
 #ck-button label {
     float:left;
     width: fit-content;
     padding: 1px 10px 0px 10px;
     font-family:Source Sans Pro;
     font-size: 18px;

 }
 
 #ck-button label span {
    text-align:center;
     padding:0px 0px;
     display:block;
     color: #ff7255;
 }
 
 #ck-button label input {
     position:absolute;
     top:-20px;
 }
 
 #ck-button input:checked + span {
     background-color:#ff7255;
     color:#fff;
     font-weight: bold;
 }

Any idea how to make the full button in orange?


Solution

  • Rule of thumb, when creating a custom checkbox always apply the styles on the clickable element. (in your case span)

    #ck-button {
      margin: 3px;
      background-color: transparent;
      overflow: auto;
      float: left;
      position: relative;
    }
    
    #ck-button span {
      box-shadow: 0px 8px 18px 0 rgba(0, 0, 0, 0.14);
      border-radius: 21px;
      border: solid 2px #ff7255;
      padding: 5px 10px;
      text-align: center;
      display: inline-block;
      color: #ff7255;
      user-select: none;
    }
    
    #ck-button label input {
      position: absolute;
      top: -20px;
    }
    
    #ck-button input:checked+span {
      background-color: #ff7255;
      color: #fff;
      font-weight: bold;
    }
    <label id="ck-button">
       <input type="checkbox" value="1" hidden/>        <span>text</span>
      </label>