Flexbox Layout
What Is It?
Flexbox arranges direct children along one main axis, either a row or a column. It is useful for alignment and distributing space.
Properties, Tags and Attributes Explained
display: flex: Makes direct children flex items.gap: Adds space between items.justify-content: Aligns or distributes items along the main axis.align-items: Aligns items along the cross axis.flex-wrap / flex: Allow wrapping and control how items grow, shrink, and start sizing.
Each example is a complete HTML page. The CSS is inside the head's style element. Use Try in new tab to edit the CSS or HTML, run your changes, and reset the example.
Example 1: Navigation row
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flexbox Layout</title>
<style>
nav { display: flex; flex-wrap: wrap; gap: 16px; align-items: center; }
a { color: #1d4ed8; }
</style>
</head>
<body>
<nav aria-label="Example navigation"><strong>Learn</strong><a href="#home">Home</a><a href="#lessons">Lessons</a></nav><p id="home">Welcome</p><p id="lessons">Choose a lesson.</p>
</body>
</html>What you see: The brand and links line up in a row and wrap when space is tight.
Example 2: Flexible cards
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flexbox Layout</title>
<style>
.cards { display: flex; flex-wrap: wrap; gap: 12px; }
.card { flex: 1 1 140px; background: #dbeafe; padding: 16px; }
</style>
</head>
<body>
<div class="cards"><div class="card">Basics</div><div class="card">Practice</div><div class="card">Project</div></div>
</body>
</html>What you see: Cards share available space and wrap below their preferred starting widths.
Example 3: Distribute space with justify-content
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flexbox Layout</title>
<style>
.row { display: flex; justify-content: space-between; align-items: center; gap: 12px; background: #eff6ff; padding: 12px; }
span { background: #bfdbfe; padding: 8px; }
</style>
</head>
<body>
<div class="row"><span>Brand</span><span>Lessons</span><span>Account</span></div>
</body>
</html>What you see: Available main-axis space goes between the items. Try center, flex-start, flex-end, space-around, and space-evenly; use this property to distribute a toolbar.
When and Where to Use It
Choose Flexbox for navigation, button rows, and aligning content along a single axis.
Common Mistake or Useful Tip
justify-content follows the main axis. With flex-direction column, that axis runs vertically.
Try It Yourself
Set flex-direction: column on the navigation.