Close

May 12, 2019

How to vertically center text in CSS Grid and Flexbox

Take this simple HTML:

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>How to Vertically Center Text</title>
		<link rel="stylesheet" href="style.css">
	</head>
	<body>
		<div class="parent">
			<p class="text">
				Center this text
			</p>
		</div>
	</body>
</html>

And, some basic styling:

body {
	font-family: sans-serif;
}

.parent {
	width: 60vw;
	padding: 3vw;
	background: #f9f9f9;
	margin: 10vh auto;
	height: 60vh;
}

.text {
	font-size: 1.5rem;
	margin-top: 0;
}

It looks like this:

Now, we want to center this text vertically. The first modern approach you can take is with flexbox. Just add these two lines to .parent:

.parent {
	display: flex;
	align-items: center;
}

And, you get this:

Simple.

It’s very similar with CSS Grid:

.parent {
	display: grid;
	align-items: center;
}

And, you can add as much text as you want and it’ll get vertically-centered properly. Like this:

So, there you go.

That said, if you want to go on learning even more HTML and CSS, check out my Website Template course on Skillshare. You’ll learn CSS Grid, CSS transitions, asynchronous requests in jQuery and more.

And, you can get access to it for free.

All the details on the course and how to get free access are here: https://www.johnmorrisonline.com/webdesign

Later,

John

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.