Center content

Center aligning content with CSS and flex-box

Center content

TLDR Flex:

display: flex;
align-items: center;
justify-content: center;

Center aligning text in CSS:

<!DOCTYPE html>
<html>
<head>
<title>center align content</title>
</head>
<body>
<h1 style="text-align: center;">🍔 is center aligned</h1>
<p>🍒 still in left</p>
</body>
</html>

Aligning content to the center:

<!DOCTYPE html>
<html>
<head>
<title>center align content</title>
</head>
<style>
body {
margin: 0;
}
.box {
height: 25rem;
background-color: blueviolet;
width: 25rem;
margin: auto;
}
</style>
<body>
<div class="box"></div>
</body>
</html>

To align an image to the center:

<!DOCTYPE html>
<html>
<head>
<title>center align content</title>
</head>
<style>
body {
margin: 0;
}
.imgCenter {
display: block;
background-color: blueviolet;
margin: auto;
}
</style>
<body>
<img
class="imgCenter"
src="https://i.chzbgr.com/full/7588073728/h78549C5D/not-sure-if-i-hate-css-or-i-hate-designers" />
</body>
</html>

Suppose you want to align a div both vertically and horizontally to the center of the parent element:

<!DOCTYPE html>
<html>
<head>
<style>
.centerBox {
margin: 0;
position: absolute;
background-color: blue;
height: 15rem;
width: 15rem;
top: 50%;
left: 50%;
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="centerBox"></div>
</body>
</html>

Using flex to align content to the center:

<!DOCTYPE html>
<html>
<head>
<title>center align content</title>
</head>
<style>
body {
margin: 0;
}
.container {
display: flex;
align-items: center;
justify-content: center;
}
.box {
width: 100px;
height: 100px;
background-color: blueviolet;
}
</style>
<body>
<div class="container">
<div class="box"></div>
</div>
</body>
</html>

Suppose you want to vertically and horizontally align a div to the center of the parent element:

<!DOCTYPE html>
<html>
<head>
<title>center align content</title>
</head>
<style>
html,
body {
height: 100%;
}
body {
margin: 0;
}
.container {
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.box {
width: 100px;
height: 100px;
background-color: blueviolet;
}
</style>
<body>
<div class="container">
<div class="box"></div>
</div>
</body>
</html>
NGA icon

© 2025 Jide Abdul-Qudus. All rights reserved.