How to center an item horizontally and vertically using CSS

The best way to center a HTML element such as a <div>, image, or text horizontally and vertically is to use Flexbox.

For the longest time, it was really annoying to try and align a HTML element both horizontally and vertically within an area on a web page.

A number of hacks were required to accomplish what one might expect to be a straightforward procedure.

Fortunately, modern browsers support using the simple Flexbox method to centering an item both horizontally and vertically using CSS.

How to center an HTML element horizontally and vertically using Flexbox

In this example, you have an item that you wish to place within a parent container that has a width and height of 600px each, and would like to have it centered horizontally and vertically within that container.

		<div class="container">
			<div class="my-item">Hello</div>

The following CSS code can be used to perform the alignment:

.container {
	width: 600px;
	height: 600px;
	display: flex;
	justify-content: center;
	align-items: center;

That’s all there is to it! The item is now centered both horizontally and vertically within the parent container.

You may also like:

Love our articles? HostM offers professional and helpful web hosting services with unlimited features and renewal rates that actually match our advertised rates.