September 18th, 2010
11:08 am
Using display:inline-block and vertical-align in CSS

Posted under CSS
Tags , , , , , ,

Update 23/11/2010

Having experimented with this extensively on different browsers, I have found inconsistent results across browsers when trying to vertically centre a group of controls in a bordered div which closely surrounds them. If you need just a few pixels between the controls and the border, vertical centering does not work in a consistent browser independent manner. For larger centring, e.g. for centring a paragraph of text in a large div, the differences may not be noticeable, but at small scale they definitely are. For placing a close border around a group of related controls, my preferred method is now to use floats as detailed here. Note that the fact that floats are used does not force the rest of the document to use floats or to have non fixed sizing – the floats can be invisible to the outside due to a second outer non floated fixed size div. Also, the floated version works better when the contained controls are of variable or unknown size.

Original post

I originally used this here in order to centre the text on a Primefaces button, the usage of inline-block was incorrect.

What it does not do is allow you for example to centre a <span> element vertically and/or horizontally in a parent div!

What it does do is to allow setting of the alignment of an inline element relative to adjacent inline elements on a line (not relative to the parent container). It will therefore work within a <td> but not within a <div>

There appear to be a lot of fuzzy and partly incorrect articles on the net about this, and it was hard to find clear definitions. even the W3schools site does not greatly help, and does not appear to list for each element whether it is an inline or block element by default, which seems quite an omission.

In the end I found some helpful posts on it here and here which cleared it up for me, and explained why my simple example of a <span> in a <div> would not centre vertically with inline-block and vertical-align:middle!

Note regarding the use of vertical-align, a typical gotcha on this is if you have a horizontal group of buttons/combos and attempt to use top/bottom margins to try to centre them vertically, you may wonder why you do not get the expected behaviour as the margins do not appear to be properly honoured. This is a classic case for using display:inline-block and vertical-align:middle on all the controls.
Primefaces note:- the Primefaces commandButton components are set to  display:inline-block by Primefaces, using the internal jQuery ui-button class.

No Comments »

Trackback URI | Comments RSS

Leave a Reply

You must be logged in to post a comment.