CSS

Created: 2019 Dec 7th

Updated: 2021 Jan 4th

Edit this page on GitHub

Center anything, horizontally and vertically, with 3 lines of CSS:

.center {
	display: flex;
	align-items: center;
	justify-content: center;
}

Via Marko ⚡ Denic

Vertically center with margin

You can use margin: auto on both display: flex and display: grid.

It will work on the child of grid or flexbox but not on a block level element.

<div class="margins">
	<p>Pls center me!</p>
</div>
.margins {
	/* display: flex; */
	display: grid;
}

.margins p {
	margin: auto;
}

Vertically center with absolute positioning

<div class="absolute">
	<p>Pls center me!</p>
</div>
.absolute {
	position: relative;
}

.absolute p {
	position: absolute;
	top: 50%;
	transform: translateY(-50%);
	width: 100%;
}

Vertically center with flexbox

<div class="flexbox">
	<p>Pls center me!</p>
</div>
.flexbox {
	display: flex;
	align-items: center;
	justify-content: center;
}

Vertically center with grid

Use either align-items: center; or place-items: center;

<div class="grid">
	<p>Pls center me!</p>
</div>
.grid {
	display: grid;
	/* align-items: center; */
	place-items: center;
}

Breaking Long Words and URLs

There are times when a really long string of text can overflow the container of a layout, use this:

.don_break_out_of_parent {
	/* These are technically the same, but use both */
	overflow-wrap: break-word;
	word-wrap: break-word;
}
Scott avatar

Made with ❤️ by Scott Spence

Copyright © 2024 - All right reserved