Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does vertical align CSS property ever work?

W3School says :

When we use vertical-align:middle; The element is placed in the middle of the parent element

So I tried to do that, But didn't get desired outcome

CODE :

div {
  height: 200px;
  width: 500px;
  background: red;
  text-align: center;
  vertical-align: middle;
}
p {
  vertical-align: middle;
}
<div>
  text
  <p>
    yo bro
  </p>
</div>

Why m I not getting the desired outcome ?

like image 372
Rasik Avatar asked Apr 18 '16 21:04

Rasik


1 Answers

because vertical-align only applies to inline level and table-cell elements. Both div and p are block level elements.

Applies to inline-level and table-cell elements. It also applies to ::first-letter and ::first-line.

MDN Source

With that in mind and using your example make your div a table and your p a table-cell

div {
  height: 200px;
  width: 500px;
  background: red;
  text-align: center;
  display: table
}
p {
  vertical-align: middle;
  display: table-cell;
}
<div>
  <p>
    yo bro
  </p>
</div>

NOTE: Don't trust W3Schools as source, instead use MDN or W3C Specs

like image 73
dippas Avatar answered Oct 05 '22 23:10

dippas