Home  >  Q&A  >  body text

Implement horizontal alignment of HTML elements in a div

<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粉431220279P粉431220279397 days ago485

reply all(2)I'll reply

  • P粉448130258

    P粉4481302582023-08-22 14:19:58

    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

    reply
    0
  • P粉798010441

    P粉7980104412023-08-22 11:43:33

    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

    reply
    0
  • Cancelreply