Material Box

Material Box

WEB Design & Material Images

CSS - Center Child Elements Vertically and Horizontally with FlexBox

CSS

How to center align child elements vertically and horizontally with CSS FlexBox, with code examples.


The HTML has a container element with class "container" and multiple <div> child elements.

<div class="container">
	<div></div><div></div><div></div><div></div><div></div>
	<div></div><div></div><div></div><div></div><div></div>
</div>

The alignment of child elements in FlexBox can be set using the "justify-content" and "align-items" properties.

"justify-content" controls alignment along the main axis.
"align-items" controls alignment along the cross axis.

By default, "justify-content" is the horizontal axis and "align-items" is the vertical axis. But if "flex-direction" makes the main axis vertical, their effects are reversed.

.container {
	width: 100%;
	display: flex;
	flex-wrap: wrap;
	justify-content: center;
	align-items: center;
	gap: 10px;
	padding: 10px;
	box-sizing: border-box;
	background-color: #404040; 
}

.container div {
	width: 80px;
	height: 80px;
	background-color: #4169e1;
}

CSS - Center Child Elements Vertically and Horizontally with FlexBox

TitleCSS - Center Child Elements Vertically and Horizontally with FlexBox

CategoryCSS

Created

Update

AuthorYousuke.U