Centering button elements and input buttons

In a recent project I needed to add a button to a column on the page. The design called for the button to be centered in the column. This turned out to be slightly less straightforward than I initially thought.

Centering elements is normally taken care of by giving them a width and auto for horizontal margins. In this case I didn’t want to set a width on the button since the site will be available in several different languages, so the amount of text on the button will differ.

My first thought was to just avoid setting a width since form controls are replaced elements and have an intrinsic width anyway once rendered by the browser, so I might be able to get away with this:

.button {
    margin:0 auto;

Sure enough, that works fine in Firefox, Safari, and Opera. But then I checked in Chrome and found the button left-aligned. Next I had a look in IE and found the same thing in IE 8. The button was centered fine in IE 9 and 7 though. Replacing the button element with input type="button" made no difference.

When looking for a fix I noticed that others have encountered this as well. There are various workarounds suggested, but what I ended up doing was adding a little bit of extra markup in the form of a span element around the button:

<span class="button">
    <button type="button">Click me!</button>

and this CSS:

.button {

I used span instead of div because I wasn’t sure whether I’d need to add more inline elements later on – a div element would work just as well and you could get rid of the display:block declaration.

After reading through the Visual formatting model details of the CSS 2.1 specification I think it’s hard to tell which, if any, of the browsers are wrong here. One the one hand, the used value for width when there is no explicitly declared width should be the element’s intrinsic width regardless of whether its display property is block, inline, or inline-block. That seems to make Chrome and IE8 wrong. On the other hand, the spec has a disclaimer regarding CSS properties on form controls:

CSS 2.1 does not define which properties apply to form controls and frames, or how CSS can be used to style them. User agents may apply CSS properties to these elements. Authors are recommended to treat such support as experimental. A future level of CSS may specify this further.

Looking at that you could say that the differing behaviour of Chrome and IE8 is not a bug, just different.

The rendering that makes margin:0 auto work for centering seems more logical to me though.

Posted on June 1, 2011 in CSS, Browsers