How to Center a div Vertically and Horizontally

We can center a div or any element vertically and horizontally by using some CSS properties. You can see below, we have used some CSS properties for aligning the child div inside the parent div.

Add HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <title>How to Center a div Vertically and Horizontally</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body style="padding: 20px">
<div class="parent-div">
    <div class="child-div"></div>
</div>
</body>
</html>

Add CSS

<style>
.parent-div {
    width: 400px;
    height: 400px;
    border: 5px solid #d93025;
    position: relative;
}
.parent-div .child-div {
    width: 100px;
    height: 100px;
    position: relative;
    background-color: #616161;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
}
</style>

Leave a Comment