Implement horizontal alignment of HTML elements in a div
P粉431220279
2023-08-22 00:03:55
<p>I have three HTML objects and want to put the Previous button on the left, the Next button on the right, and the span in the middle in a container div. </p>
<pre class="brush:php;toolbar:false;"><PREVIOUS> |SPAN| <NEXT></pre>
<p><br /></p>
<pre class="snippet-code-css lang-css prettyprint-override"><code> #btnPrevious
{
float:left;
}
#spanStage
{
font-weight:bold;
vertical-align:middle;
}
#btnNext
{
float:right;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div>
<input type="button" value="Previous" id="btnPrevious"/>
<span id="spanStage">Stage 5</span>
<input type="button" value="Next" id="btnNext"/>
</div></code></pre>
<p><br /></p>
The "display:flex" style is a great way to keep these elements on the same line. No matter what type of elements are in the div. Especially if the input class is form-control, other solutions like bootstrap, inline-block will not work well.
Example:
More details about flexbox: https://css-tricks.com/snippets/css/a-guide-to-flexbox/
flex-direction: row, column
justify-content: flex-end, center, space-between, space-around
align-items: stretch, flex-start, flex-end, center
Just add
text-align: center
to your wrapper to set the horizontal alignment of all non-floated/non-positioned child elements:<span>
Defaults to inline elements. So you can usedisplay:block
on them and style them appropriately, or adjust the parent element's style slightly. Since there are no other child elements except<span>
and<button>
, it's better to use this simple solution.Please note that
text-align:<value>
is inherited from the parent element, so if you want to include other content in the wrapper, you should checktext-align:center
Whether it is suitable for you. Otherwise, usetext-align:<value>
in a specific element, wherevalue
can beleft
,right
,center
orjustify
.JSFiddle demo