Centering divs is a basic CSS skill. Whether horizontally, vertically, or both, here are seven ways to achieve this effectively:
1. Use flexbox
Flexbox simplifies centering justify-content
and align-items
.
.parent {
display: flex;
justify-content: center; /* Horizontal */
align-items: center; /* Vertical */
height: 100vh; /* Full height */
}
2. Use grid layout
CSS Grid provides a quick way to center elements place-items
.
.parent {
display: grid;
place-items: center; /* Centers horizontally and vertically */
height: 100vh;
}
3. Use margin: auto
This method is great for horizontally centering block elements.
.child {
margin: auto;
width: 200px;
height: 100px;
}
For vertical centering, combine this with position
and transform
.
4. Use position
and transform
This technique is great for absolute positioning.
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
5. Use text alignment
For inline or inline-block elements, text-align
Center them horizontally.
.parent {
text-align: center;
}
.child {
display: inline-block;
}
6. Use table display
This method uses display: table
and display: table-cell
Used for centering.
.parent {
display: table;
height: 100vh;
}
.child {
display: table-cell;
text-align: center; /* Horizontal */
vertical-align: middle; /* Vertical */
}
7. Use line-height
for text
This method is great for placing a single line of text inside a div.
.child {
height: 100px;
line-height: 100px; /* Matches height */
text-align: center;
}
in conclusion
These seven methods cover the most common use cases for centering divs. Flexbox and Grid are ideal for modern layouts, while older methods like position
and margin
Useful for specific scenarios.
Which method do you use most often?
buy my coffee at https://ko-fi.com/codewithdhanian