Professional ways to center a div
Mohd Anas
Posted on April 3, 2023
There are several ways to center an div in CSS. Here are some professional ways:
1.Using Flexbox:
.container {
display: flex;
justify-content: center;
align-items: center;
}
2. Using Grid:
.container {
display: grid;
place-items: center;
}
3. Using Absolute Positioning:
.container {
position: relative;
}
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
4. Using Text-align Property:
.container {
text-align: center;
}
5. Using Margin Property:
.container {
width: 50%; /* or any other fixed width */
margin: 0 auto;
}
6. Using Table-cell Display:
.container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
7. Using Line-height Property:
.container {
height: 100px; /* or any other fixed height */
line-height: 100px;
text-align: center;
}
I hope the methods provided for centering a div in CSS are useful to you in achieving your desired layout for your project.
π πͺ π
π©
Mohd Anas
Posted on April 3, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.