What are the different ways to center a <div> both vertically and horizontally inside its parent, and what are the trade-offs between them? #174753
Replies: 4 comments
-
|
There are a few ways to center a 1. Absolute positioning (works well for a single child) .parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
2. Flexbox (most common approach) .parent {
display: flex;
justify-content: center;
align-items: center;
}
3. CSS Grid .parent {
display: grid;
place-content: center;
}
|
Beta Was this translation helpful? Give feedback.
-
|
Ohh great question, there are multiple way that you can have child to be perfectly centered inside .parent .parent { You have choice to use min-height that will be better for height responsiveness. On the other hand if you want to use the Position and also the transformation method you can. .parent { both are the good choice. You can use both of them.. Hope it will help you . |
Beta Was this translation helpful? Give feedback.
This comment was marked as off-topic.
This comment was marked as off-topic.
-
|
🕒 Discussion Activity Reminder 🕒 This Discussion has been labeled as dormant by an automated system for having no activity in the last 60 days. Please consider one the following actions: 1️⃣ Close as Out of Date: If the topic is no longer relevant, close the Discussion as 2️⃣ Provide More Information: Share additional details or context — or let the community know if you've found a solution on your own. 3️⃣ Mark a Reply as Answer: If your question has been answered by a reply, mark the most helpful reply as the solution. Note: This dormant notification will only apply to Discussions with the Thank you for helping bring this Discussion to a resolution! 💬 |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Select Topic Area
Question
Body
`div class="parent"
div class="child"Centered Box /div
/div`
I want .child to be perfectly centered inside .parent. Which CSS techniques can achieve this, and when would you prefer one over the other?
Beta Was this translation helpful? Give feedback.
All reactions