htmlcsscross-browseralignmentforms

How to align checkboxes and their labels consistently cross-browsers


This is one of the minor CSS problems that plague me constantly.

How do folks around Stack Overflow vertically align checkboxes and their labels consistently cross-browser?

Whenever I align them correctly in Safari (usually using vertical-align: baseline on the input), they're completely off in Firefox and IE.

Fix it in Firefox, and Safari and IE are inevitably messed up. I waste time on this every time I code a form.

Here's the standard code that I work with:

<form>
    <div>
        <label><input type="checkbox" /> Label text</label>
    </div>
</form>

I usually use Eric Meyer's reset, so form elements are relatively clean of overrides. Looking forward to any tips or tricks that you have to offer!


Solution

  • Warning! This answer is too old and doesn't work on modern browsers.

    I'm not the poster of this answer, but at the time of writing this, this is the most voted answer by far in both positive and negative votes (+1035 -17), and it's still marked as accepted answer (probably because the original poster of the question is the one who wrote this answer).

    As already noted many times in the comments, this answer does not work on most browsers anymore (and seems to be failing to do that since 2013).


    After over an hour of tweaking, testing, and trying different styles of markup, I think I may have a decent solution. The requirements for this particular project were:

    1. Inputs must be on their own line.
    2. Checkbox inputs need to align vertically with the label text similarly (if not identically) across all browsers.
    3. If the label text wraps, it needs to be indented (so no wrapping down underneath the checkbox).

    Before I get into any explanation, I'll just give you the code:

    label {
      display: block;
      padding-left: 15px;
      text-indent: -15px;
    }
    input {
      width: 13px;
      height: 13px;
      padding: 0;
      margin:0;
      vertical-align: bottom;
      position: relative;
      top: -1px;
      *overflow: hidden;
    }
    <form>
      <div>
        <label><input type="checkbox" /> Label text</label>
      </div>
    </form>

    Here is the working example in JSFiddle.

    This code assumes that you're using a reset like Eric Meyer's that doesn't override form input margins and padding (hence putting margin and padding resets in the input CSS). Obviously in a live environment you'll probably be nesting/overriding stuff to support other input elements, but I wanted to keep things simple.

    Things to note:

    I haven't tried this specific technique on any projects other than the one I was working on this morning, so definitely pipe up if you find something that works more consistently.


    Warning! This answer is too old and doesn't work on modern browsers.