June 9th, 2010
5:06 pm
Centre text and other items e.g. on a Primefaces command button

Posted under HTML
Tags , , , , ,

Update

This post originally used display:inline-block and vertical-align:middle thinking mistakenly that these were part of the fix for the problem.
See here for a more complete understanding of it.
The modified CSS below works fine just by removing the padding and setting the font.

Taking the Primefaces commandButton as an example, the label is embedded in a span:-

<button attr1=value attr2=value…>
<span>Submit</span
</button>

The button has many attributes which are not relevant to this discussion.
However, as the span is an inline element, it does not have a top/bottom margin, width or height and using text-align:center; in css has no effect.

The default Primefaces button has fixed padding for the label, which works fine by default but which is a pain when you change the size of either the button or the text.

The following rules remove the padding and set the desired font correctly to centre the text for the Primefaces commnadButton:-

.ss-textbutton {
height:20px;
width:52px;
}
.ss-textbutton > .ui-button-text {
font-size:90%;
font-weight: bold;
padding:0px;
}

This CSS is activated when the class ss-textbutton is passed to the styleClass attribute of the commandButton tag.
This example declares a 52 x 20 button. It then targets the <span> within the button using ss-textbutton > ui-button-text, as the <span> in the commandButton has the ui-button-text class. It does the following to the <span>:-

  • sets a font size and weight
  • removes all the padding, so that the centring works correctly

In this example, I have deliberately not changed all buttons globally. The Primefaces documentation explains how to use the classes  ui-button, ui-button-text and ui-button-text-only to skin all buttons globally if this is desired.

This now allows us to resize our button, change the font size and the text, and still have the label nicely centred. We don’t have to mess around with tweaking the padding and other attributes in every case, which is a whole lot simpler and more modular.

No Comments »

Trackback URI | Comments RSS

Leave a Reply

You must be logged in to post a comment.