CSS Center Align
There are several ways to center content horizontally in CSS, and the right one depends on whether you are centering a block, text, or an image.
Centering is one of the first things people want to do in CSS, and the approach changes with the kind of element. The key is knowing whether you are dealing with a block-level box, inline text, or a flex layout.
Centering a block with margin auto
A block element with a defined width can be centered by setting its left and right margins to auto. The browser splits the leftover space evenly on both sides.
margin auto
<!DOCTYPE html>
<html>
<head>
<style>
.card {
width: 320px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="card">
<p>Centered card</p>
</div>
</body>
</html>Note: margin: 0 auto only works when the element has a width narrower than its container. A full-width block has no leftover space to distribute, so nothing appears to move.
Centering inline content and text
text-align center
<!DOCTYPE html>
<html>
<head>
<style>
.banner {
text-align: center;
}
</style>
</head>
<body>
<div class="banner">
<p>Welcome to our site</p>
</div>
</body>
</html>Centering with Flexbox
justify-content
<!DOCTYPE html>
<html>
<head>
<style>
.box {
padding: 12px 20px;
background: #eee;
}
.row {
display: flex;
justify-content: center;
}
</style>
</head>
<body>
<div class="row">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
</div>
</body>
</html>Note: For horizontal and vertical centering together, Flexbox is the cleanest tool. See the Vertical Align lesson for the full pattern.