DEV Community

Cover image for Professional ways to center a div(2)
Mohd Anas
Mohd Anas

Posted on

Professional ways to center a div(2)

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);
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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%);
}
Enter fullscreen mode Exit fullscreen mode

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%;
}
Enter fullscreen mode Exit fullscreen mode

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%;
}
Enter fullscreen mode Exit fullscreen mode

13.Grid with auto margins:

.container {
 display: grid;
 place-items: center;
 height: 100vh;
}
.child {
 margin: auto;
 width: 50%;
 height: 50%;
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)