How to align checkboxes and their labels consistently cross-browsers

前端 未结 30 1839
有刺的猬
有刺的猬 2020-11-22 05:56

This is one of the minor CSS problems that plagues me constantly. How do folks around Stack Overflow vertically align checkboxes and

30条回答
  •  情话喂你
    2020-11-22 06:19

    The chosen answer with 400+ upvotes did not work for me in Chrome 28 OSX, probably because it wasn't tested in OSX or that it did work in whatever was around in 2008 when this question was answered.

    The times have changed, and new CSS3 solutions are now feasible. My solution uses pseudoelements to create a custom checkbox. So the stipulations (pros or cons, however you look at it) are as follows:

    • Only works in modern browsers (FF3.6+, IE9+, Chrome, Safari)
    • Relies on a custom designed checkbox, that will be rendered exactly the same in every browser/OS. Here I've just chosen some simple colors, but you could always add linear gradients and such to give it more of a bang.
    • Is geared to a certain font/font size, which if changed, you'd simply change the positioning and size of the checkbox to make it appear vertically aligned. If tweaked correctly, the end result should still be near to exactly the same in all browser / operating systems.
    • No vertical-alignment properties, no floats
    • Must use the provided markup in my example, it will not work if structured like the question, however, the layout will essentially look the same. If you want to move things around, you'll have to also move the associated CSS

    div.checkbox {
        position: relative;
        font-family: Arial;
        font-size: 13px;
    }
    label {
        position: relative;
        padding-left: 16px;
    }
    label::before {
        content :"";
        display: inline-block;
        width: 10px;
        height: 10px;
        background-color: white;
        border: solid 1px #9C9C9C;
        position: absolute;
        top: 1px;
        left: 0px;
    }
    label::after {
        content:"";
        width: 8px;
        height: 8px;
        background-color: #666666;
        position: absolute;
        left: 2px;
        top: 3px;
        display: none;
    }
    input[type=checkbox] {
        visibility: hidden;
        position: absolute;
    }
    input[type=checkbox]:checked + label::after {
        display: block;
    }
    input[type=checkbox]:active + label::before {
        background-color: #DDDDDD;
    }

    This solution hides the checkbox, and adds and styles pseudoelements to the label to create the visible checkbox. Because the label is tied to the hidden checkbox, the input field will still get updated and the value will be submitted with the form.

    And if you're interested, here's my take on radio buttons: http://jsfiddle.net/DtKrV/2/

    Hope someone finds this useful!

提交回复
热议问题