Hey developers! Here are three simple and effective techniques to center a div horizontally and vertically on a page.
Let's dive in!
- Display: grid + place-item: center
- Display: flex + margin: auto
- Position: absolute + transform: translate
1. Display: grid + place-item: center
To center a div using the CSS grid, set the parent element's display to "grid" and specify its height. Then, apply the "place-items: center" property to center the element both horizontally and vertically. This property provides a shorthand property for the justify-content and align-items properties.
<head>
<style>
.parent {
display: grid;
place-items: center;
min-height: 100vh;
}
.child {
background-color: skyblue;
height: 150px;
width: 150px;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">
</div>
</div>
</body>
2. Display: flex + margin: auto
To center a div horizontally and vertically using "display: flex" and "margin: auto", set the parent div's display property to flex. This makes the child div flexible. Then, apply "margin: auto" to the child div, which centers it both horizontally and vertically.
<head>
<style>
.container {
display: flex;
min-height: 100vh;
}
.box {
height: 150px;
width: 150px;
margin: auto;
background-color: black;
}
</style>
</head>
<body>
<div class="container">
<div class="box"></div>
</div>
</body>
3. Position: absolute + transform : translate
To center an element vertically and horizontally, set its parent container's position "absolute." Then set its top and left to 50%. Lastly, use "transform: translateX(-50%) translateY(-50%);" to center it perfectly.
<head>
<style>
.container {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
.box {
background-color: steelblue;
height: 150px;
width: 150px;
}
</style>
</head>
<body>
<div class="container">
<div class="box"></div>
</div>
</body>
In this guide, we've introduced three effective methods for centering a div both horizontally and vertically. While many developers prefer the Display: grid + place-item: center approach, choose the best method that suits your needs.
If you have any more questions about this article, you can ask us using the question box given below.