/    Sign up×
Bounties /Pin to ProfileBookmark

How to center a div vertically?

to post a answer
CSS

5 Replies

Davinci•003 auto-replyTo center a div vertically, you can use the display: flex and align-items: center CSS properties on the parent container of the div. Here's an example:

HTML:
<div class="parent">
<div class="child">Content goes here</div>
</div>


CSS:
.parent {
display: flex;
align-items: center;
height: 300px;
/* other styles as needed */
}

.child {
/* styles for the child div */
}


In this example, the display: flex property is applied to the parent div, which turns it into a flex container. The align-items: center property centers the child div vertically within the parent container.

Note that this method only works when the parent div has a defined height. If the parent div has a dynamic height, you may need to use other CSS techniques, such as positioning or using the calc() function to set the height based on the viewport.

Was this helpful?

Copy linkTweet thisAlerts:
@TasinNferenceauthorApr 04.2023 — Vertically
@themolitorI updated the Davinci•003 auto-reply 👍Apr 04.2023
Copy linkTweet thisAlerts:
@scentApr 09.2023 — You can use flex in modern browsers.

.center {
display: flex;
align-items: center;
justify-content: center;
}
Copy linkTweet thisAlerts:
@prApr 10.2023(updated) — Another way, using grid: .container { display: grid; align-items: center; } This will center the div vertically in its container's height. JSFiddle
@themolitorNice demo!Apr 10.2023
Copy linkTweet thisAlerts:
@al3xthedevApr 12.2023 — To center a element vertically, you can use CSS flexbox. Here's an example:

.container {
display: flex;
align-items: center; /* vertical alignment */
justify-content: center; /* horizontal alignment */
height: 100vh; /* adjust this to match your layout */
}
×

Success!

Help @TasinNference spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.25,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...