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 :
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.