How to Center a Div with Flexbox in Under 3 Minutes
6/19/20251 min read
Introduction
Centering content within a webpage is a common design requirement for front-end developers. Whether you’re creating a logo, a modal, or a card component, achieving a centered layout can enhance the visual appeal and usability of your designs. In this tutorial, we’ll walk you through the process of centering a div
element using Flexbox, a powerful CSS layout module that simplifies alignment tasks.
Step-by-Step Instructions
Here’s how to center a div
using Flexbox in just a few steps:
- Set the parent container’s display property to
flex
. - Set the flex direction to
column
if you want to center vertically orrow
for horizontal centering. - Add
justify-content: center;
to align items along the main axis. - Add
align-items: center;
to align items along the cross axis.
Copy-Paste-Ready Code Snippet
Below is a complete example with HTML and CSS:
<div class="container"> <div class="content"> Centered Content </div></div>.container { display: flex; justify-content: center; align-items: center; height: 100vh; /* Full height of the viewport */}.content { background-color: lightgray; padding: 20px; border-radius: 5px;}
Explanation of the Code
Let’s break down what each part of the code does:
display: flex;
: Enables Flexbox on the parent container, allowing for flexible layout options.justify-content: center;
: Centers the child elements horizontally within the parent container.align-items: center;
: Centers the child elements vertically within the parent container.height: 100vh;
: Sets the height of the parent container to 100% of the viewport height.- In the
.content
class: background color, padding, and border-radius improve the aesthetics of the centered content.
Common Mistakes
- Not setting the height of the parent container can result in no visual centering effect.
- Forgetting to set
display: flex;
on the parent container, which means Flexbox properties have no effect. - Using incompatible flex properties which may lead to unexpected layouts.
What to Try Next?
If you're interested in exploring more advanced layouts, consider diving into CSS Grid. Grid offers a different approach to layout design and can work effectively alongside Flexbox in your projects.
Learn
Empowering beginners in coding and development.
Guide
Support
info@codehirepath.com
© 2025. All rights reserved.