How to style a checkbox using CSS

前端 未结 30 3508
日久生厌
日久生厌 2020-11-21 04:26

I am trying to style a checkbox using the following:

30条回答
  •  醉酒成梦
    2020-11-21 04:59

    No, you still can't style the checkbox itself, but I (finally) figured out how to style an illusion while keeping the functionality of clicking a checkbox. It means that you can toggle it even if the cursor isn't perfectly still without risking selecting text or triggering drag-and-drop!

    This solution probably also fits radio buttons.

    The following works in Internet Explorer 9, Firefox 30.0 and Chrome 40.0.2214.91 and is just a basic example. You can still use it in combination with background images and pseudo-elements.

    http://jsfiddle.net/o0xo13yL/1/

    label {
        display: inline-block;
        position: relative; /* Needed for checkbox absolute positioning */
        background-color: #eee;
        padding: .5rem;
        border: 1px solid #000;
        border-radius: .375rem;
        font-family: "Courier New";
        font-size: 1rem;
        line-height: 1rem;
    }
    
    label > input[type="checkbox"] {
        display: block;
        position: absolute; /* Remove it from the flow */
        width: 100%;
        height: 100%;
        margin: -.5rem; /* Negative the padding of label to cover the "button" */
        cursor: pointer;
        opacity: 0; /* Make it transparent */
        z-index: 666; /* Place it on top of everything else */
    }
    
    label > input[type="checkbox"] + span {
        display: inline-block;
        width: 1rem;
        height: 1rem;
        border: 1px solid #000;
        margin-right: .5rem;
    }
    
    label > input[type="checkbox"]:checked + span {
        background-color: #666;
    }
    
    
    

提交回复
热议问题