Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center two divs horizontally and vertically (CSS) [duplicate]

Tags:

html

css

center

This is probably not too difficult, but for some reason - I've tried a couple of different solutions - I have some problem getting it right. I have two different div elements, a header and a textfield, that I want to center both horizontally and vertically in the middle of an enclosing div element. The header should be above the textfield.

The enclosing div element has fixed proportions, but the header varies in length and can take up just one line or more than one line.

How can I achieve this?

The HTML:

<div id="square">
    <div id="header">
        <h3>header</h3>
    </div>
    <div id="textfield">
        <input id="textfield" type="text">
    </div>
</div>

In CSS, I have tried various combinations of text-align: center, vertical-align: middle, left/right/top/bottom: 0 + margin: auto, etc, but so far I have only been able to center the divs horizontally.

In some of my solutions I have even tried having a fourth div element in between the outer and the inner ones.

like image 661
Candleout Avatar asked Nov 17 '25 05:11

Candleout


1 Answers

You can do this using display:flex:

#square {
  display: flex;
  align-items: center; /*horizontal centering*/
  justify-content: center; /*vertical centering*/
  flex-direction: column; /*keep the h3 above the textbox*/

  /* these are for demo only*/
  width: 400px;
  height: 400px;
  border:1px solid red;
}

h3 {
  margin-top:0; /* removing margin otherwise you'll get someone commenting the h3 isn't vertically centered*/
  
}
<div id="square">
    <div id="header">
        <h3>header</h3>
    </div>
    <div id="textfield">
        <input id="textfield" type="text">
    </div>
</div>
like image 171
Pete Avatar answered Nov 18 '25 21:11

Pete



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!