3

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>
Angelos Chalaris
  • 6,611
  • 8
  • 49
  • 75

2 Answers2

5

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>
Prasath V
  • 1,336
  • 4
  • 20
  • 39
  • It does, why does it do so however? How does the `margin: 0 auto` rule make it do that? – Angelos Chalaris Aug 20 '16 at 06:20
  • 2
    When you have specified a width on the object that you have applied `margin: 0 auto` to, the object will sit centrally within it's parent container. Specifying `auto` as the second parameter basically tells the browser to automatically determine the left and right margins itself, which it does by setting them equally. It guarantees that the left and right margins will be set to the same size. The first parameter 0 indicates that the top and bottom margins will both be set to 0. – Prasath V Aug 20 '16 at 06:23
1

Just add margin: 0 auto; to .leaf class.

html {
  display: table;
  height: 100%;
  width: 100%;
  text-align: center;
}
body {
  display: table-cell;
  vertical-align: middle;
}
.hidden {
  display: none;
}
.leaf {
  margin: 0 auto;
  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>
Divsign
  • 13
  • 1
  • 7
  • 1
    @Angelos, for further info about the auto trick, take a look [here](http://stackoverflow.com/questions/3170772/what-does-auto-do-in-margin0-auto) – Divsign Aug 20 '16 at 06:30