Centering Elements using Flexbox

This post provides several code snippets that make it easy for beginning (or otherwise) web designers to grab and go. Browse the library and use what is helpful.

Centering Elements

Centering elements can be particularly difficult for new web designers. I've included three code snippets for vertical, horizontal, and vertical AND horizontal centering.

Vertically Centered Element

Code Snippet (this snippet assumes the parent element has a height associated with it. You would need to add a height via CSS)

<div class="d-flex align-items-center">
	<h2>I am a vertically centered Element</h2>
</div>

Result (this result shows a 300px height on the parent element)

I am a vertically centered Element

Horizontally Centered Element

Code Snippet

<div class="d-flex justify-content-center">
	<div>I am a horizontally centered Element</div>
</div>

Result (this result shows a 300px height on the parent element)

I am a horizontally centered Element

Vertical and Horizontal Centered Element

Code Snippet

<div class="d-flex justify-content-center align-items-center">
	<div>I am a horizontally centered Element</div>
</div>

Result (this result shows a 300px height on the parent element)

I am a horizontally AND vertically centered Element

Chris Lam - Freelance Web Design and web development, denton, dallas, ft. worth, dfw