search

Home  >  Q&A  >  body text

Achieve horizontal center alignment of elements

<p>How to center one div horizontally inside another div using CSS? </p> <pre class="brush:html;toolbar:false;"><div id="outer"> <div id="inner">Foo foo</div> </div> </pre> <p><br /></p>
P粉268284930P粉268284930468 days ago518

reply all(2)I'll reply

  • P粉002023326

    P粉0020233262023-08-22 00:52:50

    If you don't want to set a fixed width on the inner div, you can try the following:

    #outer {
      width: 100%;
      text-align: center;
    }
    
    #inner {
      display: inline-block;
    }
    <div id="outer">  
        <div id="inner">Foo foo</div>
    </div>

    This will make the inner div an inline element that can be centered via text-align.

    reply
    0
  • P粉617597173

    P粉6175971732023-08-22 00:02:14

    It's very easy to center a div horizontally and vertically using flexbox.

    #inner {  
      border: 0.05em solid black;
    }
    
    #outer {
      border: 0.05em solid red;
      width:100%;
      display: flex;
      justify-content: center;
    }
    <div id="outer">
      <div id="inner">Foo foo</div>
    </div>

    reply
    0
  • Cancelreply