CSS Flexbox (Flexible Box Layout)
The name Flexbox is a short form of the CSS Flexible Box Layout module.
As a layout model, it arranges items inside a container either horizontally or vertically, flexibly and responsively.
You get flexible, responsive layouts with little effort, and neither float nor positioning is required.
Flexbox vs. Grid: The difference is dimensions. Flexbox handles one at a time (rows OR columns), while CSS Grid handles two (rows AND columns).
Example
Five flex items sit in a row inside one flex container.
Prompt
Create a flex container with a blue (DodgerBlue) background containing five flex items labeled "Item 1" through "Item 5". Each item should have a light gray (#f1f1f1) background, 10px margin, 20px padding, and 30px font size.
Output: complete HTML page
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Five Flex Items</title>
<style>
.container {
display: flex;
background-color: DodgerBlue;
}
.container div {
background-color: #f1f1f1;
margin: 10px;
padding: 20px;
font-size: 30px;
}
</style>
</head>
<body>
<div class="container">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
<div>Item 4</div>
<div>Item 5</div>
</div>
</body>
</html>
CSS Flexbox Components
Every flexbox has two parts:
- A Flex Container — the parent element, whose
displayproperty has the valueflexorinline-flex. - One or more Flex Items — any direct child of the container becomes one automatically.
A Flex Container with Three Flex Items
In the example below, the blue area is the flex container, and it holds three flex items.
The following chapters go deeper into both containers and items.
Example
Three flex items inside one flex container.
Prompt
Create a flex container with a DodgerBlue background containing three flex items labeled "Item 1", "Item 2", and "Item 3". Each item should have a light gray (#f1f1f1) background, 10px margin, 20px padding, and 30px font size.
Output: complete HTML page
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Three Flex Items</title>
<style>
.container {
display: flex;
background-color: DodgerBlue;
}
.container div {
background-color: #f1f1f1;
margin: 10px;
padding: 20px;
font-size: 30px;
}
</style>
</head>
<body>
<div class="container">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
</div>
</body>
</html>