How would you vertically center an element within its parent container, regardless of the parent's height?
Loading
How would you vertically center an element within its parent container, regardless of the parent's height?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Rajkiran SwainRank #165 · 14.4K reputationPosted Jun 4, 2023, 12:20 PM EDT
Centered Content .parent-container { display: flex; align-items: center; justify-content: center; }Deepak RawatRank #646 · 3.7K reputationPosted Jun 6, 2023, 5:53 AM EDT
To vertically center an element within its parent container, regardless of the parent's height, you can use CSS and apply the following techniques:
Method 1: Flexbox: You can easily center an element vertically within its parent container. Here's an example:
HTML:
CSS:
.parent { display: flex; align-items: center; /* Vertically center the child */ }Method 2: CSS Transforms You can use CSS transforms to vertically center an element by translating it. Here's an example:
HTML:
CSS:
.parent { position: relative; } .child { position: absolute; top: 50%; transform: translateY(-50%); /* Vertically center the child */ }Method 3: CSS Table Display You can use the table display properties to achieve vertical centering. Here's an example:
HTML:
CSS:
.parent { display: table; width: 100%; } .child { display: table-cell; vertical-align: middle; /* Vertically center the child */ }These methods provide different approaches to vertically center an element within its parent container. Choose the one that best suits your specific needs and coding preferences.