How to style a disabled checkbox?

后端 未结 9 652
旧巷少年郎
旧巷少年郎 2021-01-07 16:32

Do you know how I could style a checkbox when it is disabled?

E.g.:



        
9条回答
  •  北荒
    北荒 (楼主)
    2021-01-07 16:51

    You can't style a disabled checkbox directly because it's controlled by the browser / OS.

    However you can be clever and replace the checkbox with a label that simulates a checkbox using pure CSS. You need to have an adjacent label that you can use to style a new "pseudo checkbox". Essentially you're completely redrawing the thing but it gives you complete control over how it looks in any state.

    I've thrown up a basic example so that you can see it in action: http://jsfiddle.net/JohnSReid/pr9Lx5th/3/

    Here's the sample:

    input[type="checkbox"] {
        display: none;
    }
    
    label:before {
        background: linear-gradient(to bottom, #fff 0px, #e6e6e6 100%) repeat scroll 0 0 rgba(0, 0, 0, 0);
        border: 1px solid #035f8f;
        height: 36px;
        width: 36px;
        display: block;
        cursor: pointer;
    }
    input[type="checkbox"] + label:before {
        content: '';
        background: linear-gradient(to bottom, #e6e6e6 0px, #fff 100%) repeat scroll 0 0 rgba(0, 0, 0, 0);
        border-color: #3d9000;
        color: #96be0a;
        font-size: 38px;
        line-height: 35px;
        text-align: center;
    }
    
    input[type="checkbox"]:disabled + label:before {
        border-color: #eee;
        color: #ccc;
        background: linear-gradient(to top, #e6e6e6 0px, #fff 100%) repeat scroll 0 0 rgba(0, 0, 0, 0);
    }
    
    input[type="checkbox"]:checked + label:before {
        content: '✓';
    }

    Depending on your level of browser compatibility and accessibility, some additional tweaks will need to be made.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题