Implement horizontal alignment of HTML elements in a div
P粉431220279
P粉431220279 2023-08-22 00:03:55
0
2
509
<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>
P粉431220279
P粉431220279

reply all(2)
P粉448130258

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:

<div style="display:flex; flex-direction: row; justify-content: center; align-items: center">
     <input type="button" value="Previous" id="btnPrevious"/>
     <span id="spanStage">Stage 5</span>
     <input type="button" value="Next" id="btnNext"/>
</div>

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

P粉798010441

Just add text-align: center to your wrapper to set the horizontal alignment of all non-floated/non-positioned child elements:

div{
    text-align:center;
}

<span>Defaults to inline elements. So you can use display: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 check text-align:centerWhether it is suitable for you. Otherwise, use text-align:<value> in a specific element, where value can be left, right, center or justify.

JSFiddle demo

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!