How to align checkboxes and their labels consistently cross-browsers

前端 未结 30 1858
有刺的猬
有刺的猬 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:08

    The following gives pixel-perfect consistency across browsers, even IE9:

    The approach is quite sensible, to the point of being obvious:

    1. Create an input and a label.
    2. Display them as block, so you can float them as you like.
    3. Set the height and the line-height to the same value to ensure they center and align vertically.
    4. For em measurements, to calculate the height of the elements, the browser must know the height of the font for those elements, and it must not itself be set in em measurements.

    This results in a globally applicable general rule:

    input, label {display:block;float:left;height:1em;line-height:1em;}
    

    With font size adaptable per form, fieldset or element.

    #myform input, #myform label {font-size:20px;}
    

    Tested in latest Chrome, Safari, and Firefox on Mac, Windows, Iphone, and Android. And IE9.

    This method is likely applicable to all input types that are not higher than one line of text. Apply a type rule to suit.

提交回复
热议问题