Flexbox - Beginner's guide...
Table of contents
- Five things to know about Flexbox
- What is Flexbox?
- Why Flexbox Matters in Modern Web Design
- Flexbox’s Core Strengths
- Understanding the Flex Container and Flex Items
- Flex Items and Their Properties
- Use Cases
- Mastering the Flex Direction and Flex Wrap Properties
- Flex-Grow, Flex-Shrink, and Flex-Basis
- Real-World Application: Adaptive Card Layouts
- Conclusion
Five things to know about Flexbox
As you'll discover, numerous ways to rearrange items on a web page exist. Over time, new ways have emerged, while old ones have fallen out of favour. Flexbox wasn't always accessible in CSS, and its introduction was groundbreaking.
So with that said, dear reader, here are five things you should know about Flexbox.
What is Flexbox?
Flexbox is simply a method for arranging elements into rows or columns. These items will flex (i.e. grow or shrink) based on rules you can set. It allows you to style the flex container without having to style the actual items inside the container.
To get started, let us look at a demo.
The picture above shows the codes on the left and the life browser on the right. The size and shape of the flexbox can easily be adjusted using the codes.
Why Flexbox Matters in Modern Web Design
For years, CSS layout relied on methods like floats, inline-block elements, and even tables. While these approaches worked to an extent, they often required complex workarounds and careful calculation of widths, margins, and paddings.
For example, with floats, developers would need to clear floats manually to maintain layout integrity, and with inline blocks, they’d face unwanted whitespace between elements.
Flexbox changes the game by creating a layout model that’s designed for flexibility and alignment right out of the box. Its approach is based on the concept of a “flex container” that controls “flex items” within it.
By defining the relationship between the container and its items, Flexbox enables effortless layout control that would have been nearly impossible—or incredibly time-consuming—using older CSS techniques.
Flexbox’s Core Strengths
Flexbox shines in a few areas that make it essential for modern web design:
Effortless Alignment and Distribution
One of Flexbox’s standout features is its ability to align items along both horizontal and vertical axes effortlessly. With just a few properties, you can centre items perfectly within a container or distribute space between them equally.
This control simplifies the alignment process, especially for complex layouts.
Flexibility and Responsiveness
As the name implies, Flexbox is designed to be flexible. It’s built for dynamic resizing, making it ideal for responsive design. Unlike previous layout methods, Flexbox allows elements to grow, shrink, or maintain specific proportions based on the available space, making it easy to create layouts that adapt to different screen sizes.
Direction Control
Flexbox introduces the concept of a “flex-direction” property, which allows items to be displayed in either a row or column format.
This flexibility opens up more design possibilities without the need to rearrange HTML markup. With a quick adjustment in CSS, you can switch between horizontal and vertical layouts—a feature that wasn’t as straightforward before Flexbox.
That’s enough good being spoken about flexbox, now let’s move to the next topic, flexbox elements. This section will teach the basics of Flexbox.
Understanding the Flex Container and Flex Items
Flexbox introduces a different approach to arranging elements in CSS. The foundational concept behind Flexbox is that everything begins with a flex container—it’s the environment that enables flexible behaviour for its child elements, known as flex items.
Once a container is set as “flex,” its direct children adapt automatically to Flexbox rules, allowing for much more control over alignment, spacing, and responsiveness.
The Flex Container
The flex container is any HTML element that’s been assigned display: flex
or display: inline-flex
. By setting this, you essentially turn the container into a flexible box that governs how its direct children (the flex items) behave and align within it.
Flex containers create a specific environment for the items within, making it easier to arrange and control layout properties like alignment, spacing, and order, without needing extra CSS hacks.
Unlike traditional layouts, where items often need manual margins, paddings, or floats, Flexbox simplifies the setup by having the container take care of these alignments through properties like justify-content
and align-items
. Once you understand how the flex container works, you can unlock powerful, responsive layouts without relying on complex CSS workarounds.
Here’s a quick example of creating a basic flex container.
```css
.container {
display: flex;
/\ Add flex-direction, justify-content, or align-items as needed */*
}
```
In HTML, the structure might look like this:
```html
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
</div>
```
With just display: flex
, the container is now a flex container, and its child item elements become flex items, ready to be aligned and adjusted as needed.
Flex Items and Their Properties
So, what exactly are flex items?
They’re simply the direct children of a flex container. Flex items are special because Flexbox treats them with a unique set of rules that allow for flexible alignment, ordering, and sizing. This makes them fundamentally different from traditional layout models like block
or inline-block
.
For example, Flexbox introduces properties like flex-grow
, flex-shrink
, and flex-basis
, which controls how an item expands, contracts, or occupies space within the container.
These properties are applied to individual items, allowing them to adjust their size and spacing dynamically based on the available space in the flex container. This type of dynamic sizing is nearly impossible to achieve with regular CSS alone.
Use Cases
The flex container and flex items model shines in scenarios where you need responsive, adaptable layouts that automatically adjust to screen size, content quantity, or container dimensions. Here are a few places where using Flexbox makes a lot of sense:
Navigation Bars
Flex containers make it easy to align navigation items horizontally and centre them or distribute them evenly.
Card Layouts
Flexbox works perfectly for laying out cards in a row or grid, where the number of items might change but should still fit evenly across a row.
Footer Sections
You can align footer items side-by-side and ensure they stay balanced across different screen sizes without excessive padding or margin adjustments.
Flexible Grids
Flexbox enables you to set up grids where items wrap onto new lines as needed, making it perfect for responsive designs that need to scale down for smaller screens.
Flexbox simplifies layouts that would otherwise require a complex combination of CSS properties, media queries, and manual spacing. By understanding the role of the flex container and how it impacts flex items, you gain a robust toolset for creating elegant, responsive layouts with minimal code.
Mastering the Flex Direction and Flex Wrap Properties
To use the Flexbox model, you need to first create a Flex container.
The flex container's attributes are:
flex-direction
flex-wrap
flex-flow
justify-content
align-items
align-content
The Flex-direction Property
The flex-direction parameter specifies which direction the container intends to stack the flex components.
This creates the main axis, which determines which direction flex objects are placed in the flex container. Flexbox (apart from optional wrapping) is a one-direction layout concept. Think of flex elements as largely arranged in horizontal rows or vertical columns.
Flex-wrap
The flex-wrap property controls whether items should wrap onto multiple lines or stay on a single line within the flex container. This is especially useful for responsive design, as it allows items to adapt to smaller screen sizes. It has three values:
nowrap: Default; all items will stay on one line, even if they overflow the container.
wrap: Allows items to wrap onto multiple lines from top to bottom.
wrap-reverse: Similar to wrap, but wraps items from bottom to top.
This attribute is essential when you want your layout to adapt naturally without needing additional media queries.
Flex-flow
flex-flow is a shorthand property that combines both flex-direction and flex-wrap into a single line. Instead of specifying each property separately, you can use flex-flow to streamline your code.
For instance, flex-flow: row wrap; sets items in a row and allows them to wrap onto new lines as needed. It’s a convenient option that keeps your CSS concise and organized.
Justify-content
The justify-content property determines how flex items are aligned along the main axis of the container (horizontal if flex-direction is a row, vertical if it’s a column). It offers several values:
flex-start: Aligns items to the start of the container.
flex-end: Aligns items to the end of the container.
centre: Centers items along the main axis.
space-between: Distributes items with equal space between them, aligning the first and last items at the edges.
space-around: Distributes items with equal space around each item.
space-evenly: Similar to space-around, but adds equal space between items and at the edges.
This property allows precise control over spacing, making it easy to achieve perfectly balanced layouts with minimal effort.
Align-items
While justify-content aligns items along the main axis, align-items controls alignment along the cross-axis (the opposite direction). This attribute affects how items are aligned vertically if flex-direction is row, or horizontally if it’s column. It has these options:
stretch: Default; items stretch to fill the container along the cross-axis.
flex-start: Aligns items to the start of the cross-axis.
flex-end: Aligns items to the end of the cross-axis.
centre: Centers items along the cross axis.
baseline: Align items so that their baselines align with each other.
This property is especially useful for ensuring uniform alignment across items, even if they vary in size.
Align-content
Align-content controls how multiple lines of items are aligned along the cross-axis when there’s extra space in the container. It’s only effective when flex-wrap is enabled and there are multiple lines of items. Here are its values:
flex-start: Lines are packed toward the start of the cross-axis.
flex-end: Lines are packed toward the end of the cross-axis.
centre: Lines are centred along the cross-axis.
space-between: Lines are evenly distributed, with no space at the edges.
space-around: Lines are evenly distributed, with equal space around each line.
stretch: Default; lines stretch to fill the remaining space.
With align-content, you can achieve more complex layouts by controlling the spacing and alignment of lines of items, making your layout both flexible and visually pleasing.
Flex-Grow, Flex-Shrink, and Flex-Basis
These three properties are the key ingredients in Flexbox’s dynamic layout magic. Together, they control how flex items expand, contract, and use space within a flex container. Let’s break down each property and see how they work individually before diving into shorthand syntax.
Flex-grow
The flex-grow
property dictates how much an item should grow relative to the other items within the same container when there’s extra space.
This value is typically set as a number. For example, if one item has a flex-grow
of 2
and another has a flex-grow
of 1
, the first item will take up twice as much extra space as the second item.
Example:
```css
.item {
flex-grow: 1; /\ Each item grows equally */*
}
```
```css
.item-one {
flex-grow: 2; /\ Grows twice as fast as item-two */*
}
.item-two {
flex-grow: 1;
}
```
In the first example, all items flex-grow: 1
would expand equally. In the second example, the first item will take up more space because its flex-grow
value is larger.
Flex-shrink
The flex-shrink property controls how items shrink relative to each other when space is limited. Like flex-grow, it takes a numerical value.
Setting flex-shrink to 0
makes an item resistant to shrinking, while a positive integer value allows it to shrink relative to other items in the container. It’s especially useful for preventing important elements from becoming too small when space gets tight.
Example:
```css
.item {
flex-shrink: 1; /\ Items will shrink equally */*
}
```
```css
.item-one {
flex-shrink: 0; /\ Won't shrink when space is limited */*
}
.item-two {
flex-shrink: 1;
}
```
In this example, item-one won’t shrink at all, while item-two will reduce in size as needed.
Flex-basis
The flex-basis property sets the initial size of a flex item before any extra space is added or reduced based on flex-grow
and flex-shrink
. It acts as a starting point or “base size” for the item. This can be set in any CSS length unit (pixels, percentages, etc.), allowing you to give each item a default size.
Example:
```css
.item {
flex-basis: 200px; /\ Sets a fixed initial size */*
}
```
By setting flex-basis: 200px
, each item will start at 200 pixels wide (or higher, depending on the flex-direction) before any adjustments for flex-grow
or flex-shrink
kick in.
The Flex Shorthand Property
Flexbox allows you to combine flex-grow
, flex-shrink
, and flex-basis
into a single shorthand property: flex
. This shorthand syntax reduces clutter, letting you set all three properties at once.
The syntax is: flex: [flex-grow] [flex-shrink] [flex-basis]
.
Example:
```css
.item {
flex: 1 1 200px; /\ Equivalent to flex-grow: 1, flex-shrink: 1, flex-basis: 200px */*
}
```
If you omit flex-shrink
or flex-basis
, the shorthand automatically fills in default values (usually 1
for flex-shrink
and 0
for flex-basis
).
Comparison Example:
```css
/\ Separate properties */*
.item {
flex-grow: 1;
flex-shrink: 1;
flex-basis: 200px;
}
/\ Shorthand */*
.item {
flex: 1 1 200px;
}
```
Using shorthand not only makes your CSS cleaner but also helps maintain consistency across items.
Real-World Application: Adaptive Card Layouts
Now, let’s see how flex-grow
, flex-shrink
, and flex-basis
can work together to create responsive card layouts that adjust based on screen size.
Imagine a set of cards where you want them to expand to fill available space on larger screens but stack neatly on smaller ones.
HTML Structure:
```html
<div class="container">
<div class="card">Card 1</div>
<div class="card">Card 2</div>
<div class="card">Card 3</div>
</div>
```
CSS Styling:
```css
.container {
display: flex;
flex-wrap: wrap;
}
.card {
flex: 1 1 200px; /\ Grows and shrinks as needed, starts at 200px */*
margin: 10px;
padding: 20px;
background-color: #f4f4f4;
}
```
With flex: 1 1 200px
, each card starts at 200px in width but can grow to fill the container or shrink down on smaller screens.
As the viewport changes, Flexbox recalculates each item’s size to best fit the available space. This setup is perfect for card layouts, making them responsive without relying on media queries.
By understanding and combining these properties, you can use Flexbox to build adaptive, visually appealing, and user-friendly layouts that respond to your users' screens and provide an optimal browsing experience.
Conclusion
Hello there, thanks for reading this far! The next section of this lesson is on building responsive layouts with Flexbox. I’d love to continue, but this article has gone way longer than I expected, so I’ll go over it in my next article. I’ll see you in the next one.
Subscribe to my newsletter
Read articles from Onueze Mmasinachukwu directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Onueze Mmasinachukwu
Onueze Mmasinachukwu
I'm Onueze Mmasinachukwu, a Technical writer and a frontend developer. My articles are focused on web development. I love reading, writing and sharing my ideas with people.