Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

CSS vertical-align: middle; not working for display: inline-block; on paragraph element?

body {
  vertical-align: middle;
  text-align: center;
}

#paragraph {
  display: inline-block;
  background-color: greenyellow;
  width: 50%;
}
<body>
  <p id="paragraph">
    Lorem ipsum dolor sit amet consectetur, adipisicing elit. Culpa deserunt veniam reprehenderit sunt dolorem placeat, reiciendis aliquam perspiciatis porro, at eaque nisi et corrupti. Officia placeat labore esse blanditiis unde culpa earum amet enim, quibusdam.
  </p>
</body>

My goal is to center align the #paragraph horizontally and vertically with respect to the body container.
By setting the display of #paragraph to inline-block, I centered the paragraph horizontally with text-align: center;. Then, I tried to vertically center the paragraph with vertical-align: middle;, but wasn’t working.
Please how do I center #paragraph vertically?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Instead of styles related to text (inline level), use styles related to block-level elements (p is a contextual block level tag) – for example CSS flex can do the trick pretty easily, then on the desired child element use margin: auto; to make it centered both vertically and horizontally.

* { margin: 0; box-sizing: border-box; }

html {
  height: 100%;
}

body {
  min-height: 100%;
  display: flex;
}

#paragraph {
  margin: auto;
  background-color: greenyellow;
  width: 50%;
}
<p id="paragraph">
  Lorem ipsum dolor sit amet consectetur, adipisicing elit. Culpa deserunt veniam reprehenderit sunt dolorem placeat, reiciendis aliquam perspiciatis porro, at eaque nisi et corrupti. Officia placeat labore.
</p>

PS: margin: auto; on the child element is a better solution than justify-content: center; align-items: center; on the flex parent, specially if you need the child element position: fixed/absolute like i.e: a modal popup centered in the viewport area.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading