SITERAW

[CSS] How to center text vertically

Author Message
Ordo # Posted two hours ago
Vertical alignment of a div block Hello.

I have a text contained within a <div> that I want to center both horizontally, which I managed to do with text-align: center;, and also vertically something that I haven't managed to do yet.

I tried using padding with a percentage but the problem is that the text doesn't stay centered when the amount of text changes.

Is there any equivalent to text-align for vertically centering text inside a <div> ?

Thanks !
Ads
Rel0ad # Posted one hour ago
Rel0ad Sigh... http://www.siteraw.com/html-css/how-to-create-a-website/flexbox-layouts
Phoenix # Posted 37 minutes ago
Phoenix There is more than one way to align an element on the vertical axis.

Method 1 - Flexbox


As Rel0ad said, it is covered in depths in the SiteRaw tutorial.
.container {
display: flex;
align-items: center;
justify-content: center;
}

Method 2 - Transform & translate


Alternatively, you could also use this method which will work on most browsers.
.container {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}

Method 3 - Table cell


In some cases, you will need to ensure that the html / body element's height is set to 100%.
.parent {
height: 100%;
display: table;
}
.parent > .child {
display: table-cell;
vertical-align: middle;
}

Method 4 - Absolute positioning


This approach assumes that the text has a known height (20 pixels in the demo) so I only recommend it as a last resort. We use a negative margin to vertically center our content.
.container > p {
position: absolute;
top: 50%;
margin-top: -10px;
}

Method 5 - Line height


This is the least flexible method, for educational purposes only.
.container {
line-height: 50%;
}
Ordo # Posted 5 minutes ago
Ordo Thanks, it works as intended.

I'll remember the flexbox model from now on.

Post a reply