Date : 17th December 2024

For all the latest browsers

Five ways to horizontal and vertical center text in a DIV

#1 This is centered text using absolute and translate

#2 This is centered text using display: flex

#3 This is centered text using align-content

#4 This is centered text using place-content

#5 This is centered text using display: grid

Information

There have been many ways to center text in a DIV both horizontally and vertically over the past few years.

With this demonstration I have brought all the methods together to show how simple it has become.

All the above start with the same HTML and basic CSS.

HTML
<div class="block">
<h1>This is centered text ... etc ...</h1>
</div>

CSS
.block {width:30%; min-width:250px; aspect-ratio:3/2; margin:20px auto; background:#000; border-radius:0.5cqw;}
.block h1 {font:2.3cqh 'Raleway', arial, sans-serif; text-align:center; width:70%; margin:auto; color:#fff; border:1px solid #888; border-radius:0.25cqw;}

A specific id and # number is then added to each div.

The CSS styles for each version are as follows:

#1
#one {position:relative;}
#one h1 {position:absolute; width:75%; top:50%; left:50%; transform:translate(-50%, -50%); padding:0; margin:0;}

#2
#two {display:flex; justify-content:center; align-items:center;}

#3
#three {align-content:center;}

#4
#four {place-content:center;}

#5
#five {display:grid; place-items:center;}

Please consider making a donation, every little helps.