Mohd Anas
Posted on April 21, 2023
There are more ways to center an div in CSS,
Let's check old seven eight ways: https://dev.to/lyfperegrine/professional-ways-to-center-a-div-46eo
8.Perspective and Transform:
.container {
position: relative;
perspective: 1000px;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%) translateZ(0);
}
9.Clip-path:
.container {
position: relative;
height: 100vh;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 50%;
height: 50%;
clip-path: circle(50% at center);
}
10.SVG:
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<rect x="0" y="0" width="100" height="100" fill="transparent" />
<foreignObject width="100%" height="100%">
<div class="child">Centered Content</div>
</foreignObject>
</svg>
/* CSS */
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
11.Flexbox with pseudo-elements:
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container::before,
.container::after {
content: "";
flex: 1;
}
.child {
width: 50%;
height: 50%;
}
12.Background-size:
.container {
background: url('image.jpg') no-repeat;
background-size: contain;
background-position: center;
height: 100vh;
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 50%;
height: 50%;
}
13.Grid with auto margins:
.container {
display: grid;
place-items: center;
height: 100vh;
}
.child {
margin: auto;
width: 50%;
height: 50%;
}
I hope the methods we provided for centering a div in CSS will be helpful for you to achieve your desired layout in your project.
💖 💪 🙅 🚩
Mohd Anas
Posted on April 21, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.