Search code examples
htmlcsscenter

Center two divs horizontally and vertically (CSS)


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.


Solution

  • Does this work?

    #square {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      border: 1px solid #ccc;
    }
    <div id="square">
      <div id="header">
        <h3>header</h3>
      </div>
      <div id="textfield">
        <input id="textfield" type="text">
      </div>
    </div>