How to align checkboxes and their labels consistently cross-browsers

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

    Sometimes vertical-align needs two inline (span, label, input, etc...) elements next to each other to work properly. The following checkboxes are properly vertically centered in IE, Safari, FF, and Chrome, even if the text size is very small or large.

    They all float next to each other on the same line, but the nowrap means that the whole label text always stays next to the checkbox.

    The downside is the extra meaningless SPAN tags.

    .checkboxes label {
      display: inline-block;
      padding-right: 10px;
      white-space: nowrap;
    }
    .checkboxes input {
      vertical-align: middle;
    }
    .checkboxes label span {
      vertical-align: middle;
    }

    Now, if you had a very long label text that needed to wrap without wrapping under the checkbox, you'd use padding and negative text indent on the label elements:

    .checkboxes label {
      display: block;
      padding-right: 10px;
      padding-left: 22px;
      text-indent: -22px;
    }
    .checkboxes input {
      vertical-align: middle;
    }
    .checkboxes label span {
      vertical-align: middle;
    }

提交回复
热议问题