gigi gigi - 3 months ago 10
CSS Question

Align HTML elements horizontally in a div

I have three HTML objects and want to arrange Previous button at the left side, Next button at right side and span in the middle inside a container div.

<PREVIOUS> |SPAN| <NEXT>


HTML

<div>
<input type="button" value="Previous" id="btnPrevious"/>
<span id="spanStage">Stage 5</span>
<input type="button" value="Next" id="btnNext"/>
</div>


CSS

#btnPrevious
{
float:left;
}
#spanStage
{
font-weight:bold;
vertical-align:middle;
}
#btnNext
{
float:right;
}

Answer

Just add text-align: center to your wrapper to set the horizontal alignment of all non-floating/non-positioned children:

div{
    text-align:center;
}

<span> are inline elements by default. Thus you either have to use display:block on them and style them appropriately, or just tweak the parent style a little bit. Since there are no other children than the <span> and the <button>s your best of with this simple solution.

Note that text-align:<value> gets inherited from the parent, so if you want to include something else in your wrapper you should check whether text-align:center is okay for you. Otherwise use text-align:<value> in the specific element, where value is left, right, center or justify.

JSFiddle Demo