Intro to Flexbox: Grid of Widgets

The Problem

Floating widgets works fine if you only have one row of them, but if you have multiple rows, the widgets must all be the same height to reflow properly as screen size shrinks. If they have different heights, this may happen:

taller widgets block the reflow of floats as the screen narrows

The Solution

Remove floats and side margins from the widgets, and set flexbox properties on their container:

Widget 1

Praesent mollis commodo porta. Proin sit amet mi felis. Nam rutrum eget elit a tempus. Nam a pulvinar ligula. Sed ultricies pulvinar nulla eget efficitur.

Widget 2

This is the tallest widget. All other widgets in the same row must flex to match its height.

Vestibulum vulputate est eu odio faucibus commodo. Praesent auctor, urna a pellentesque ornare, dolor ex tempor metus, quis rhoncus urna lorem tempus arcu.

Widget 3

Praesent mollis commodo porta. Proin sit amet mi felis. Nam rutrum eget elit a tempus. Nam a pulvinar ligula. Sed ultricies pulvinar nulla eget efficitur.

Widget 4

Vestibulum vulputate est eu odio faucibus commodo. Praesent auctor, urna a pellentesque ornare, dolor ex tempor metus, quis rhoncus urna lorem tempus arcu.

Widget 5

This is the tallest widget. All other widgets in the same row must flex to match its height.

Praesent mollis commodo porta. Proin sit amet mi felis. Nam rutrum eget elit a tempus. Nam a pulvinar ligula. Sed ultricies pulvinar nulla eget efficitur.

Widget 6

Vestibulum vulputate est eu odio faucibus commodo. Praesent auctor, urna a pellentesque ornare, dolor ex tempor metus, quis rhoncus urna lorem tempus arcu.

Widget 7

Praesent mollis commodo porta. Proin sit amet mi felis. Nam rutrum eget elit a tempus. Nam a pulvinar ligula. Sed ultricies pulvinar nulla eget efficitur.

Widget 8

Vestibulum vulputate est eu odio faucibus commodo. Praesent auctor, urna a pellentesque ornare, dolor ex tempor metus, quis rhoncus urna lorem tempus arcu.

Widget 9

Praesent mollis commodo porta. Proin sit amet mi felis. Nam rutrum eget elit a tempus. Nam a pulvinar ligula. Sed ultricies pulvinar nulla eget efficitur.

The Code


.flexcontainer {	/* we set flex properties on the container element */
	background-color: #C4C4C4;
	display: flex;
	flex-wrap: wrap;
	justify-content: space-between;
}


.widget {	/* child elements have no floats or side margins */
	width: 30%;
	margin-bottom: 2em;
	padding: 1.5em;
	background-color: #70201C;
	color: #FFF;
}


.widget:nth-of-type(3n+2) {   /* every third widget, starting with #2 */
	background-color: #313F4D;
}


@media screen and (max-width: 750px) {

.widget {
	width: 48%;
}

.widget:nth-of-type(3n) {
	width: 100%;
}
}

@media screen and (max-width: 500px) {


.widget {
	width: 100%;	
}
}

Additional Flexbox Resources