How to Center Div Inside Div [Horizontally & Vertically]
When it comes to web development, centering a <div>
inside another <div>
both horizontally and vertically can be a bit tricky. However, with a few simple techniques, you can achieve this without pulling your hair out. In this guide, we’ll walk you through the steps to center a <div>
inside another <div>
using clean and effective methods.
HTML Structure
Before diving into the techniques, it’s important to understand the structure. You have a parent <div>
(outer <div>
) and a child <div>
(inner <div>
) that you want to center inside the parent. For simplicity, let’s assume the parent has a defined width and height.
<div class="parent">
<div class="child">
<!-- Content goes here -->
</div>
</div>
Centering Horizontally
a. Using Flexbox
Flexbox is a layout model that makes centering elements a breeze. Apply the following styles to the parent <div>
:
.parent {
display: flex;
justify-content: center; /* Horizontally centers child */
}
b. Using CSS Grid
CSS Grid is another powerful option:
.parent {
display: grid;
place-items: center; /* Centers both horizontally and vertically */
}
Centering Vertically
a. Using Flexbox
To vertically center the child <div>
using Flexbox:
.parent {
display: flex;
align-items: center; /* Vertically centers child */
}
b. Using CSS Grid
For vertical centering with CSS Grid:
.parent {
display: grid;
align-items: center; /* Vertically centers child */
}
Centering Both Horizontally and Vertically
a. Using Flexbox
For vertical and horizontal centering using flexbox CSS:
.parent {
display: flex;
justify-content: center; /* Horizontally centers child */
align-items: center; /* Vertically centers child */
}
b. Using CSS Grid
For vertical and horizontal centering with CSS Grid:
.parent {
display: grid;
align-items: center; /* Vertically centers child */
}
Remember, the above methods assume that the child <div>
has a specific width and height.
Conclusion
Centering a <div>
inside another <div>
might seem like a puzzle, but with Flexbox, CSS Grid, and a touch of positioning, you can achieve pixel-perfect centering without losing your sanity.