3

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.

Candleout
  • 305
  • 3
  • 13

2 Answers2

4

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>
Pete
  • 57,112
  • 28
  • 117
  • 166
2

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>
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252