Angelos Chalaris Angelos Chalaris - 3 months ago 7
HTML Question

Div not centered when using display: table-cell

I have been using

display: table
for my
html
along with
display: table-cell
for my
body
lately, to make all of the contents of my page appear at the very center of the screen. While, this works with paragraphs, headings, inputs and labels etc.(as far as I have tested at least), it doesn't seem to work with
div
elements.

Is there any way to make this work for
div
elements like it does for the other ones? Pure CSS solution would be best.

Example (also on Codepen)



html {
display: table;
height: 100%;
width: 100%;
text-align: center;
}
body {
display: table-cell;
vertical-align: middle;
}
.hidden {
display: none;
}
.leaf {
border-radius: 15px 2px 15px 2px;
border: 1px solid green;
background-color: green;
width: 250px;
height: 80px;
}

<div class="leaf">Why am I not centered?</div>
<p>And why am I centered?</p>




Answer

Just add margin: 0 auto;.. Working right.

html {
  display: table;
  height: 100%;
  width: 100%;
  text-align: center;
}
body {
  display: table-cell;
  vertical-align: middle;
}
.hidden {
  display: none;
}
.leaf {
  border-radius: 15px 2px 15px 2px;
  border: 1px solid green;
  background-color: green;
  width: 250px;
  height: 80px;
  margin:0 auto;

}
<div class="leaf">Why am I not centered?</div>
<p>And why am I centered?</p>