0% found this document useful (0 votes)
3 views50 pages

Flex Box

This guide provides an in-depth overview of the CSS Flexbox layout system, highlighting its advantages over traditional float and position properties for creating responsive web designs. It explains the concept of flex containers and items, the main and cross axes, and various properties used to manipulate layout, alignment, and ordering of elements. Additionally, the guide discusses when to use Flexbox versus CSS Grid and includes practical examples for implementing Flexbox in web design.

Uploaded by

Prabin Magar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views50 pages

Flex Box

This guide provides an in-depth overview of the CSS Flexbox layout system, highlighting its advantages over traditional float and position properties for creating responsive web designs. It explains the concept of flex containers and items, the main and cross axes, and various properties used to manipulate layout, alignment, and ordering of elements. Additionally, the guide discusses when to use Flexbox versus CSS Grid and includes practical examples for implementing Flexbox in web design.

Uploaded by

Prabin Magar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 50

A Guide to CSS Flexbox

When you add HTML content to your web page, it stacks on top of itself, leaving a lot of
space on the edges or making your content look odd. The float CSS property, along
with position, was then used to define layouts and position elements, but it was
complicated to use, especially when dealing with responsiveness.

You no longer need to use the float and position properties to organize your page’s layout
and style containers or content side by side. With the advancement of the web and
technology, you now have two CSS layout systems: flexbox and CSS grid. This guide
focuses on CSS flexbox, but you can bookmark our detailed guide on CSS grid.

This guide will teach you everything you need to know about the CSS flexbox layout
system, including the flexbox layout axis and its properties, justifying and aligning flex
items, adding gaps and ordering these elements, and much more. You’ll also learn when to
use flexbox and when to use CSS grid by the end of this guide.

What is Flexbox?

CSS flexbox is a one-dimensional layout system that you can use to create a row or column
axis layout. It is a module rather than a single property because it includes several
properties, some of which are for the flex container (parent element) and others for the
flex items (children elements). This layout module allows the container to change its items’
width/height (and order) to fit the available space best and support all display devices and
screen sizes.

CSS flexbox was introduced in 2009 as a new layout system to make it easier to build
responsive web pages and organize your elements, and it has grown in popularity since
then. Flex is designed to provide a more efficient way of laying out all items, aligning, and
distributing space among each item in a container, even when each flex item’s sizes are
unknown and/or dynamic.

It simplifies designing and building responsive web pages by eliminating the need for
tricky hacks and a plethora of float and position properties in your CSS code. Flexbox
allows you to automatically scale elements (change their height or width) to fill the
available space, shrink or grow elements to fit into the container, and prevent overflow. It
can change the order of the items, create columns of the same height, design navigation
panels, and much more.

CSS is comprised of many different layout algorithms, known officially as “layout modes”.
Each layout mode is its own little sub-language within CSS. The default layout mode
is Flow layout, but we can opt in to Flexbox by changing the display property on the parent
container.

The “Flexible Box” or “Flexbox” layout mode offers an alternative to Floats for defining the
overall appearance of a web page. Whereas floats only let us horizontally position our
boxes, flexbox gives us complete control over the alignment, direction, order, and size of
our boxes.
Understand the Flexbox Layout Axis

When we flip display to flex, we create a “flex formatting context”. This means that, by
default, all children will be positioned according to the Flexbox layout algorithm.

Each layout algorithm is designed to solve a specific problem. The default “Flow”
layout is meant to create digital documents; it's essentially the Microsoft Word layout
algorithm. Headings and paragraphs stack vertically as blocks, while things like text, links,
and images sit inconspicuously within these blocks.

So, what problem does Flexbox solve? Flexbox is all about arranging a group of items
in a row or column, and giving us a ridiculous amount of control over the distribution and
alignment of those items. As the name suggests, Flexbox is all about flexibility. We can
control whether items grow or shrink, how the extra space is distributed, and more.

Is it still relevant?

You might be wondering: now that CSS Grid is well-supported in modern browsers, isn't
Flexbox obsolete?

CSS Grid is a wonderful layout mode, but it solves different problems than
Flexbox. We should learn both layout modes, and use the right tool for the job.

Flexbox still reigns supreme when it comes to dynamic, fluid UIs that arrange items in a
vertical or horizontal list. We'll see an example in this guide, the deconstructed pancake,
that can't easily be accomplished with CSS Grid.

Honestly, as someone comfortable with both CSS Grid and Flexbox, I still find myself
reaching for Flexbox quite often!

The way items are laid out when you use flexbox is based on the flex directions. If the flex-
direction is row which is the default value, your main axis is along the row, and your cross-
axis is along the column. If the flex-direction is column, your main axis is along the column
while your cross-axis is along the row.
By default, the main axis goes horizontally across the container, and the cross-axis goes
vertically.

The primary axis in which flex items are laid out in a flex container is usually referred to as
the main axis. It is not necessarily horizontal because it depends on the flex-
direction property. The cross-axis is perpendicular to the main axis. Its direction depends
on the main-axis direction.

Items will be laid out following either the main axis (from main-start to main-end) or the
cross axis (from cross-start to cross-end).

 main axis – The main axis of a flex container is the primary axis along which flex items
are laid out. Beware, it is not necessarily horizontal; it depends on the flex-
direction property (see below).

 main-start | main-end – The flex items are placed within the container starting from
main-start and going to main-end.

 main size – A flex item’s width or height, whichever is in the main dimension, is the
item’s main size. The flex item’s main size property is either the ‘width’ or ‘height’
property, whichever is in the main dimension.

 cross axis – The axis perpendicular to the main axis is called the cross axis. Its
direction depends on the main axis direction.

 cross-start | cross-end – Flex lines are filled with items and placed into the container
starting on the cross-start side of the flex container and going toward the cross-end
side.

 cross size – The width or height of a flex item, whichever is in the cross dimension, is
the item’s cross size. The cross size property is whichever of ‘width’ or ‘height’ that is
in the cross dimension.

The main axis and the cross-axis

The first thing you need to understand about Flexbox is the concept of axes. Every flex
container (an element with a display property set to flex or inline-flex) has a main axis and
a cross axis.

The main axis is either horizontal or vertical depending on the value of the flex-direction.
No worries if you are not familiar with flex-direction. You are about to learn it.
The cross axis and main axis when the flex-direction is row

In this example, the main axis is horizontal and the cross axis is vertical.

The following is an example where the the main axis is vertical and the cross axis, is
horizontal.

The main axis and cross axis when the flex-direction is column

Flexbox properties

Flexbox is a module, meaning it comprises many properties that are either applied to the
flexbox container or the flex items. Here is a table to show the list of elements that you can
apply to either the flex container or items:

Flex container Flex Items


display order
flex-direction flex-grow
flex-wrap flex-shrink
flex-flow flex-basis
justify-content flex
align-items align-self
align-content
gap, row-gap, column-
gap

How to make a flex container

The flex container is a container that holds all the flex items. For example, if you have
a div that holds three other divs:

<div class="flex-container">
<div class="flex-item">
<p>Item One</p>
</div>
<div class="flex-item">
<p>Item Two</p>
</div>
<div class="flex-item">
<p>Item Three</p>
</div>
</div>

To make the parent div a flex container, you would apply the display property and give it a
value flex. This turns the container into a block element, allowing a flex layout for all of its
direct children.

.flex-container {
display: flex;
}

You can also set the value to inline-flex, which works similarly. The only difference is that
it creates a container as an inline element.

.flex-container {
display: inline-flex;
}

An absolutely-positioned flex item does not participate in flex layout.

Understanding flex and inline-flex

You can use both flex and inline-flex to make an element a flex container. The difference is
in how they interact with surrounding elements.

display: flex

This makes the flex container behave like a block-level element. The flex-container takes
up the entire available width of its parent element. It starts on a new line, and the element
that comes after it also starts on a new line.

Example:

<button>Button One</button>

/* Flex Container */
<section class="container">
<div id="red"></div>
<div id="gold"></div>
<div id="green"></div>
</section>

<button>Button Two</button>
.container {
display: flex;
}
Flex containers behave like block elements when you use display: flex

The .container element takes up the entire available width of the body (its parent
element).

display: inline-flex

This makes the flex-container behave like an inline-level element. This allows other inline
elements (like buttons) to flow alongside it. Using the previous example, this is how the
elements will be arranged when you change display from flex to inline-flex.

Flex containers behave like inline-elements when you use display: inline-flex

The flex container does not take up the entire width of its parent. It uses only as much
horizontal space as necessary for its content.

How to set flex-direction

You can set the direction of your flex items using the flex-direction property. You can set
the items to flex vertically (column), horizontally (row), or even reverse the items in the
specified direction using values like row-reverse and column-reverse.

.flex-container {
display: flex;
flex-direction: row | row-reverse | column | column-reverse;
}

The flex-direction property will only work on a flex container, meaning you must have used
the display property and set the value to flex or inline-flex.

Now, let's look at some examples to see how it all works.

In the following code snippet, we have a names-container with four names:

<div class="names-container">
<p id="jill">1. JILL</p>
<p id="john">2. JOHN</p>
<p id="jane">3. JANE</p>
<p id="jack">4. JACK</p>
</div>

Let's see the different ways you can arrange the names using the flex-direction property.

flex-direction: row

This displays the flex-items horizontally from left to right.

.names-container {
display: flex;
flex-direction: row;
/* Other styles here... */
}

flex-direction: column

This displays the flex-items vertically from top to bottom.

flex-direction: row-reverse

This is the opposite of the row value. It displays the flex items from right to left.

flex-direction: column-reverse

This is the opposite of the column value. It displays the flex items from the bottom to the
top.
The default value of flex-direction is row which sets the flex items from left to right. In
contrast, row-reverse does the opposite and sets flex items right to left. column will set
flex items from top to bottom with items order similar to row, while column-reverse will
reverse the flex items from bottom to top.

Ordering Vs. Reordering

When talking about flexbox ordering, we need to make clear the difference
between ordering and reordering.

What is Ordering?

When we set up a flexbox layout we first need to define the source order, meaning we have
to decide how the axes of the flex
container are positioned.

In brief, each flex container has two axes:


the main axis and the cross axis. The
main axis will have one of four directions,
and the cross axis will always be
perpendicular to that:

1. left to right
2. right to left
3. top to bottom
4. bottom to top

The cross axis is always perpendicular to the main axis.

We set up the main axis with the flex-direction property, then we decide how flex items
will wrap, using the flex-wrap property. These two properties determine how the browser
will lay out the items within the flex container.

So What is Reordering?

Flexbox also lets us manipulate the default source order, effectively reordering, with the
help of the order property. Reordering means that we change the visual rendering of the
items, while the source order remains intact.

If we use the reordering capabilities of flexbox, we don’t have to change the HTML
document structure just for the sake of visual presentation. So, screen reader users (and
search engines) can get the content in a logically structured way (e.g. the sidebar won’t
take precedence over the main content).

Flexbox Ordering
Flexbox ordering happens with the flex-direction and flex-wrap properties. Flex-
direction specifies the direction of the main axis. It can take the following values:

1. row (default) main axis: left to right


2. row-reverse main axis: right to left
3. column main axis: top to bottom
4. column-reverse main axis: bottom to top

Flex-wrap defines if flex items are laid out in a single line or wrap to multiple lines. It also
controls the direction of the cross axis. It can have three values:

1. nowrap (default) lays out flex items in a single line; the cross axis stands in the default
position
2. wrap lays out flex items in multiple lines; the cross axis stands in the default position
3. wrap-reverse lays out flex items in multiple lines; the cross axis is reversed

The default position of the cross axis is:

 top to bottom in case of row and row-reverse


 left to right in case of column and column-reverse

Flexbox Reordering

It’s time to look at things a little differently.

The order property changes the default ordering of flex items that we define with flex-
direction and flex-flow. It only affects the visual rendering of the items, so it doesn’t affect
the way how screen readers and other non-CSS user agents read the source code.

As opposed to the properties mentioned before, we use order on the flex items, instead of
the flex container. It can take any integer value, and its default value is 0.

The following example moves .item-3 to the starting point of the main axis. As all items
have 0 as default value, it’s enough to use the order: -1 rule to make it the first item within
the container:

.item-3 {
order: -1;
}

Ordering and Accessibility

The most important thing to understand about all this is that the order property doesn’t
affect the painting, speech, and sequential navigation orders. This means that when we
modify the order of our flex items, users of non-visual media won’t experience the changes.
For example, people relying on keyboard navigation will still move through the links in the
original source order.
In Search of the Holy Grail by Matthew Levine January 30, 2006 - I’m sorry. Really. I
didn’t name it. I don’t mean to overstate its importance or trivialize the other and rather
weightier Holy Grails. But the name’s out there, and we all know what it means.

Three columns. One fixed-width sidebar for your navigation, another for, say, your Google
Ads or your Flickr photos—and, as in a fancy truffle, a liquid center for the real substance.
Its wide applicability in this golden age of blogging, along with its considerable difficulty,
is what has earned the layout the title of Holy Grail.

This flexbox behavior can come in handy in some cases. For instance, it’s possible to make
the so-called “Holy Grail Layout” accessible with the help of flexbox ordering. The Holy
Grail Layout is the popular blog layout with a header, a footer, and two sidebars: one on
the left and one on the right of the main content.

In this layout, we usually put the left sidebar before the main content in the HTML code.
However, from the point of view of accessibility, users of assistive technologies should
encounter the main content first. Flexbox is perfect for this. We can place the main
content before the two sidebars in our markup. Then, we only need to put the sidebar and
the main content into the correct position using the order property:

.sidebar-left {
order: 1;
}
article {
order: 2;
}
.sidebar-right {
order: 3;
}

Holy Grail Layout

The Holy Grail Layout is a classic CSS problem with various solutions presented over time.
At its core, the Holy Grail Layout is a page with a header, footer, and three columns. The
center column contains the main content, and the left and right columns contain
supplemental content like ads or navigation.
Most CSS solutions to this problem aim to meet a few goals:

 They should have a fluid center with fixed-width sidebars.


 The center column (main content) should appear first in the HTML source.
 All columns should be the same height; regardless of which column is actually the
tallest.
 They should require minimal markup.
 The footer should “stick” to the bottom of the page when content is sparse.

Unfortunately, because of the nature of these goals and the original limitations of CSS,
none of the classic solutions to this problem were ever able to satisfy all of them.

With Flexbox, a complete solution is finally possible.

The HTML

<body class="HolyGrail">
<header>…</header>
<div class="HolyGrail-body">
<main class="HolyGrail-content">…</main>
<nav class="HolyGrail-nav">…</nav>
<aside class="HolyGrail-ads">…</aside>
</div>
<footer>…</footer>
</body>

The CSS

Getting the center content row to stretch and the footer to stick to the bottom is what we
need. The only difference is the center row of the Holy Grail layout (.HolyGrail-body) needs
to be display:flex in order to properly arrange its children.

.HolyGrail {
display: flex;
min-height: 100vh;
flex-direction: column;
}

.HolyGrail-body {
display: flex;
flex: 1;
}

Styling three equal-height columns with a fluid center and fixed-width sidebars is just as
easy:

.HolyGrail-content {
flex: 1;
}

.HolyGrail-nav, .HolyGrail-ads {
/* 12em is the width of the columns */
flex: 0 0 12em;
}

.HolyGrail-nav {
/* put the nav on the left */
order: -1;
}

Note: the CSS required to make this demo work cross-browser is slightly different from
the CSS shown in the examples above, which assume a fully spec-compliant browser.

Being Responsive

The Holy Grail layout came from an era of Web design when pretty much everyone was
browsing on a computer. But with the increasing number of mobile devices and the rising
popularity of responsive design, the Holy Grail layout has gone mostly out of fashion.

Either way, with Flexbox, creating a mobile-first and mobile-friendly version of the Holy
Grail layout is easy. The gist is to simply make the center section flex-direction:column by
default and then flex-direction:row for larger screens.

Here’s a complete example that is responsive and mobile-first. You can also resize this
browser window to see it in action.

.HolyGrail,
.HolyGrail-body {
display: flex;
flex-direction: column;
}

.HolyGrail-nav {
order: -1;
}

@media (min-width: 768px) {


.HolyGrail-body {
flex-direction: row;
flex: 1;
}
.HolyGrail-content {
flex: 1;
}
.HolyGrail-nav, .HolyGrail-ads {
/* 12em is the width of the columns */
flex: 0 0 12em;
}
}

Wrapping flex Items

Most of the time when we work in two dimensions, we'll want to use CSS Grid, but Flexbox
+ flex-wrap definitely has its uses! This particular example showcases the “deconstructed
pancake” layout, where 3 items stack into an inverted pyramid on mid-sized screens.

When we set flex-wrap: wrap, items won't shrink below their hypothetical size. At
least, not when wrapping onto the next row/column is an option!

But wait! What about our kebab / cocktail weenie metaphor??


With flex-wrap: wrap, we no longer have a single primary axis line that can skewer each
item. Effectively, each row acts as its own mini flex container. Instead of 1 big skewer,
each row gets its own skewer:

All of the rules we've learned so far continue to apply, within this reduced scope. justify-
content, for example, will distribute the two pieces on each stick.

But hmm... How does align-items work, now that we have multiple rows? The cross
axis could intersect multiple items now!

Sometimes, the space within the flex container will not be enough for the flex items. In
such cases, you use the flex-wrap property to choose whether to let the flex-items overflow
or begin on a new line.

The flex-wrap property accepts any of the following values:

 nowrap (default value)


 wrap
 wrap-reverse

To see flex-wrap in action, let's add four more names to our names-container:

<div class="names-container">
<p id="jill">1. JILL</p>
<p id="john">2. JOHN</p>
<p id="jane">3. JANE</p>
<p id="jack">4. JACK</p>
<p id="sara">5. SARA</p>
<p id="seth">6. SETH</p>
<p id="seal">7. SEAL</p>
</div>

flex-wrap: nowrap

This keeps all the flex items on a single line either in a row or column. It allows the flex
items to overflow if there's not enough room in the flex container. See the example below:

.names-container {
display: flex;
flex-direction: row;
flex-wrap: nowrap;
/* Other styles here... */
}
In this example, three names overflow out of the container because there is not enough
space for them.

flex-wrap: wrap

This will wrap or push the flex items to the next line if there's not enough room for them.

flex-wrap: wrap-reverse

This is the opposite of wrap. It moves the overflow items to the next line but in a reverse
direction.

For example, using wrap-reverse on the names container moves overflow items to the next
top line instead of the next line below.

The flex-flow Shorthand Property

The flex-flow property is a shorthand for the flex-


direction and flex-wrap properties. This means that when
you use flex-flow, you can apply both properties with only a
single line of code.

See the example below using the names container. You can
give the container flex-direction and flex-wrap properties.

.names-container {
display: flex;
flex-direction: column;
flex-wrap: wrap;
}

Or you can use the flex-flow shorthand to get the same result.

.names-container {
display: flex;
flex-flow: column wrap;
}

How to align items along the main axis

After you’ve got a flex container, your next job is to


define the horizontal alignment of its items. That’s
what the justify-content property is for. We can use it
to center our .menu, like so:

.menu-container {
/* ... */
display: flex;
justify-content: center; /* Add this */
}

This has the same effect as adding a margin: 0


auto declaration to the .menu element. But, notice how
we did this by adding a property to the parent element
(the flex container) instead of directly to the element
we wanted to center (the flex item). Manipulating
items through their containers like this is a common
theme in flexbox, and it’s a bit of a divergence from
how we’ve been positioning boxes thus far.

The justify-content Property

This justify-content property handles the alignment of flex items on the main axis of the
flex container.

The justify-content property defines the horizontal alignment of flex items. This property
has six major values that perform individual functions, all aimed at exerting some control
over the alignment of flex items.

.flex-container {
justify-content: flex-start | flex-end | center | space-between | space-
around | space-evenly;
}

 flex-start: This is the default value in which flex items are packed toward the start of
the main axis or flex-direction.

 flex-end: This is the opposite of flex-start, as flex items are packed toward the end of
the main axis or flex-direction.
 center: This perfectly fits the flex items within the flex container. Other options, such as
start, end, left, and right, do what the value indicates. For example, when you set a
value to right, the flex items will be packed toward the container’s right edge.

 space-between: This option evenly distributes flex items in the line starting and ending
on the flex container border, except for padding or margin.

 space-around: This option will evenly distribute flex items in line with equal space
around them (left, right, bottom and top). It is important to know that between each
element, the gap won’t be the same as the top and bottom because this is the sum of
the gap on the right and left of both elements.

 space-evenly: This creates an exact space between each flex item, ensuring that the
space between any two items and the edges is equal.

justify-content: flex-start

This places the items at the start of the flex-direction. If the main axis is horizontal with
a flex-direction of row (like the example below), it aligns the items to the left. And if it's
vertical (with a flex-direction of column), it aligns the items to the top.

Using the names container example, this is how justify-content: flex-start would look like:

.names-container {
display: flex;
justify-content: flex-start;
/* Other styles here... */
}

justify-content: flex-end

This will place the flex items at the end of the flex-direction of the main axis.

justify-content: center

This places the flex items at the center of the flex container's main axis.

justify-content: space-between

This will place the first flex item at the start of the main axis. And also place the last item
at the end of the main axis. Then space on the main axis is distributed equally among the
the elements.
justify-content: space-evenly

This distributes space equally among the flex items. This means the space before and after
each item is the same.

justify-content: space-around

This also distributes space equally between the flex items. The key difference here is that
the space before the first item and after the last item is half the space between the flex
items.

The various values of justify-content and how they help justify flex items.

Content vs. items

So, based on what we've learned so far, Flexbox might seem pretty arbitrary. Why is
it justify-content and align-items, and not justify-items, or align-content?

For that matter, why is there an align-self, but not a justify-self??

These questions get at one of the most important and misunderstood things about
Flexbox. To help me explain, I'd like to use a metaphor.

In Flexbox, items are distributed along the primary axis. By default, they're nicely lined up,
side-by-side. I can draw a straight horizontal line that skewers all of the children, like
a kebab?:

The cross axis is different, though. A straight vertical line will only ever intersect one of
the children.

It's less like a kebab, and more like a group of cocktail wieners?:
There's a significant difference here. With the cocktail wieners, each item can move along
its stick without interfering with any of the other items:

By contrast, with our primary axis skewering each sibling, a single item can’t move along
its stick without bumping into its siblings! Try dragging the middle piece side to side:

This is the fundamental difference between the primary/cross axis. When we're
talking about alignment in the cross axis, each item can do whatever it wants. In
the primary axis, though, we can only think about how to distribute the group.

That's why there's no justify-self. What would it mean for that middle piece to set justify-
self: flex-start? There's already another piece there!

With all of this context in mind, let's give a proper definition to all 4 terms we've been
talking about:

 justify — to position something along the primary axis.


 align — to position something along the cross axis.
 content — a group of “stuff” that can be distributed.
 items — single items that can be positioned individually.

And so: we have justify-content to control the distribution of the group along the primary
axis, and we have align-items to position each item individually along the cross axis. These
are the two main properties we use to manage layout with Flexbox.
There's no justify-items for the same reason that there's no justify-self; when it comes to
the primary axis, we have to think of the items as a group, as content that can be
distributed.

What about align-content? Actually, this does exist within Flexbox! We'll cover it a little
later on, when we talk about the flex-wrap property.

Hypothetical size

Let's talk about one of the most eye-opening realizations I've had about Flexbox.

Suppose I have the following CSS:

.item {
width: 2000px;
}

A reasonable person might look at this and say: “alright, so we'll get an item that is 2000
pixels wide”. But will that always be true?

<style>
.flex-wrapper {
display: flex;
}
.item {
width: 2000px;
}
.row {
list-style-type: none;
padding: 16px;
}
.item {
height: 50px;
border: 2px solid;
border-radius: 4px;
background: hotpink;
margin: 16px;
}
</style>
<div class="item"></div>
<div class="flex-wrapper">
<div class="item"></div>
</div>

This is interesting, isn't it?

Both items have the exact same CSS applied. They each have width: 2000px. And yet,
the first item is much wider than the second!
The difference is the layout mode. The first item is being rendered using Flow layout, and
in Flow layout, width is a hard constraint. When we set width: 2000px, we'll get a 2000-
pixel wide element, even if it has to burst through the side of the viewport like the Kool-
Aid guy?.

In Flexbox, however, the width property is implemented differently. It's more of a


suggestion than a hard constraint.

The specification has a name for this: the hypothetical size. It's the size an
element would be, in a perfect utopian world, with nothing getting in the way.

Alas, things are rarely so simple. In this case, the limiting factor is that the parent doesn't
have room for a 2000px-wide child. And so, the child's size is reduced so that it fits.

This is a core part of the Flexbox philosophy. Things are fluid and flexible and can adjust to
the constraints of the world.

How to align items along the cross-axis

Asides from aligning items along the main axis, you can also do for the cross-axis using
the align-items property. Just like the justify-content property, align-items also has about
five values that can be used to align flex items.

The align-items Property

The align-items property handles the alignment of flex items on the cross-axis of the flex
container. It can take any of the following values:

.flex-container {
display: flex;
align-items: stretch | flex-start | flex-end
| center | baseline;
}

 stretch: By default, flex items are stretched to fill the


flex container, still respecting min-width and max-
width properties.

 flex-start: This places all flex items at the start of the cross-axis based on the flex-
direction. Other values similar to this are start and self-start.

 flex-end: This is the opposite of flex-start, as flex items are placed at the end of the
cross-axis. Other values similar to this are end and self-end.

 center: This places flex items in the center along the cross-axis.

 baseline: All flex items are aligned in the sense that their baselines are aligned.

align-items: stretch

This stretches the flex items to fill up the space within the flex-container.

In our example I set the height of the first child to initial which is essentially the same as if
we had never set a height on the first child. By default when a div has no height it will just
be the height of the content inside of it, but as you can see below the first child fills the full
height of the container since it is stretching to fill the full height. The second element is
not stretching, though, since we set a specific height of 100px on it. This is the default
behavior of align-items.

.flex-container {
display: flex;
align-items: stretch;
}

.flex-item:nth-child(1) {
/* This is the same as if we had not set a height */
height: initial;
}

See the example below using a new names container with name cards of different sizes:

.names-container {
display: flex;
align-items: stretch;
/* Other styles here... */
}

align-items: flex-start

This will place the flex items at the start of the cross-axis of the flex container. If the cross-
axis is vertical like in the example below, align-items: flex-start will place the items at the
top.

.names-container {
display: flex;
align-items: flex-start;
/* Other styles here... */
}
align-items: flex-end

This will place the flex items at the end of the cross-axis of the flex container. If the cross-
axis is vertical like in the example below, align-items: flex-end will place the items at the
bottom.

.names-container {
display: flex;
align-items: flex-end;
/* Other styles here... */
}

Example of align-items: flex-end

align-items: center

This aligns flex items at the center of the cross-axis of the flex container.

.names-container {
display: flex;
align-items: center;
/* Other styles here... */
}
align-items: baseline

When you use the baseline value, flex items are arranged such that their baselines are
aligned. See the example below:

.names-container {
display: flex;
align-items: baseline;
/* Other styles here... */
}

The align-content Property

When you have a flex container with wrap (or more than one flex line), you may need to
align the lines to distribute the space as you want. That is when you use align-content.

align-items works with the one-line flex items, while you can use the align-
content property to define the vertical alignment of multiple lines of items. This
property has no effect when only one line of flex items exists.

In multiple line flexible containers, the align-content property will not work unless flex-
wrap is set to wrap or wrap-reverse.

.flex-container {
display: flex;
align-content: stretch | flex-start | flex-end | center | space-between |
space-around;
}

The justify-content property is used to align individual


items on the main axis, but you can also use align-
content for the cross-axis when you want to space the
items, move them to the start or end of the cross-axis,
or stretch them.

 flex-start: This can be used to move all your flex


items to the start of the flex container based on
the flex-direction. This is also similar to
using start.

 flex-end / end: This is the opposite of flex-


start or start. The flex items are moved to the end
of the flex container. This is also similar to
using end.

 center: All flex items are placed at the center of


the flex container.

 space-between: This will space all flex items


evenly, starting and ending on the edge of the flex
container.

 space-around: This helps you evenly distribute equal space around each flex item. You
can also make use of space-evenly for perfect spacing.

 stretch: flex items are stretched to take up the entire space.

align-content: stretch - This stretches the flex lines to fill up the space within the flex
container's cross-axis.

.names-container {
display: flex;
flex-wrap: wrap;
align-items: stretch;
/* Other styles here... */
}
align-content: flex-start - This places the flex lines at the start of the container's cross-
axis. For example, if the cross axis is vertical like that of the names container, it will place
the flex lines at the top.

align-content: flex-end - This places the flex lines at the end of the container's cross-
axis.

align-content: center - This places the flex lines at the center of the container's cross-
axis.
align-content: space-between - This will place the first flex line at the start of the cross-
axis. It also places the last flex line at the end of the cross axis. Then space on the cross-
axis is distributed equally between the the lines.

align-content: space-evenly - This distributes space equally between the flex lines. This
means the space before and after each line is the same.
align-content: space-around - This also distributes space equally between the flex lines.
The key difference here is the space before the first line and after the last line is half the
space between the flex lines.

align-content: stretch - This stretches the flex lines to fill up the space within the flex
container's cross-axis.

.names-container {
display: flex;
flex-wrap: wrap;
align-items: stretch;
/* Other styles here... */
}

align-content: flex-start - This places the flex lines at the start of the container's cross-
axis. For example, if the cross axis is vertical like that of the names container, it will place
the flex lines at the top.
align-content: flex-end - This places the flex lines at the end of the container's cross-
axis.

align-content: center - This places the flex lines at the center of the container's cross-
axis.
align-content: space-between - This will place the first flex line at the start of the cross-
axis. It also places the last flex line at the end of the cross axis. Then space on the cross-
axis is distributed equally between the the lines.

align-content: space-evenly - This distributes space equally between the flex lines. This
means the space before and after each line is the same.

align-content: space-around - This also distributes space equally between the flex lines.
The key difference here is the space before the first line and after the last line is half the
space between the flex lines.
The order property

The order property determines the order of appearance for the flex items. The value you
give to this property must be a number. A flex item with a lower number will appear before
one with a higher number. In the HTML code, the order for the four names is as follows:

1. Jill
2. John
3. Jane
4. Jack

<div class="names-container">
<p id="jill">1. JILL</p>
<p id="john">2. JOHN</p>
<p id="jane">3. JANE</p>
<p id="jack">4. JACK</p>
</div>

You can change the order of appearance on the screen using the order property. See the
example below.

Here's how they appear with no order properties:

Now, see how they appear when you add the following order properties:

.names-container {
display: flex;
}

#jill {
order: 2;
background-color: #fe4f46;
}
#john {
order: 4;
background-color: #fcd65c;
}

#jane {
order: 1;
background-color:
#00bab4;
}

#jack {
order: 3;
background-color: #003f54;
}

The order property changes the order of appearance

Word of caution: Even though the order of appearance changes on screen, the order in
the HTML remains unchanged. And it's the order in the HTML that screen readers use.
Where possible, it's best practice to change the order in the HTML rather than doing it
with Flexbox.

The align-self property

You can use the align-self property to give a flex item a different alignment from the other
items. It works the same way as the align-items property. The difference is that
whereas align-items applies to all flex items, the align-self property is applied to only
specific items.

Example:

.names-container {
display: flex;
align-items: center;
/* Other styles */
}

#jill {
align-self: flex-start;
}
In the example, the align-items property for the names container has a value of center.
This aligns all the names at the center.

But using the align-self property, you are able to align Jill's name card to the top with a
value of flex-start.

Growing and shrinking / Filling up Free Space

One of the most challenging aspects of writing CSS is figuring out how to allocate the free
space that remains on the screen after the page has been populated with content. At some
viewport sizes, you’ll often find there’s too much remaining space and you want to fill it
with something. At other viewport sizes, you might find there’s not enough space, and the
layout breaks in one way or another.

So, we've seen that the Flexbox algorithm has some built-in flexibility, with hypothetical
sizes. But to really see how fluid Flexbox can be, we need to talk about 3 properties: flex-
grow, flex-shrink, and flex-basis.

1. flex-grow: how flex items should behave when there’s a surplus of free space (how they
should grow).

2. flex-shrink: how flex items should behave when there’s a shortage of free space (how
they should shrink).

3. flex-basis: how flex items should behave when there’s exactly as much space as needed.

The flex-grow property

When you set a container's display to flex, often there will be some extra space after the
items are arranged. We can specify how that space should be consumed with the flex-grow
property.

The default value for flex-grow is 0, which means that growing is opt-in. If we want a child
to gobble up any extra space in the container, we need to explicitly tell it so.

What if multiple children set flex-grow? In this case, the extra space is divvied up
between children, proportionally based on their flex-grow value.

When a single child is given a positive flex-grow value, it gobbles up all of the extra space.
In this case, it doesn't matter what the number is: 1 and 1000 have the same effect.

See the example below:

.names-container {
display: flex;
justify-content:
flex-start;
/* Other styles */
}

The flex container has more than enough space for the flex items

The browser treats the extra as a value of 1. This means when you give a flex-grow value
of 0.5 to only one of the flex items, the browser will add half of the remaining space to the
item's size.

#jill {
flex-grow: 0.5;
}

The flex-grow property makes the Jill's larger than its initial size

And if you add a flex-grow value of 1 to only one of the flex items, the browser will add
all the extra space to that item.

NOTE: If only one item in the container has a flex-grow value, then any value of 1 or more
will make it take up all the extra space.

For example, the two code snippets below will have the same effect on Jill's card:

#jill {
flex-grow: 1;
}
#jill {
flex-grow: 99;
}

When only one card has a flex-grow of 1 or more

What happens when you add flex-grow values to more than one element?

The browser will share the extra space proportionately for them.

For example, when you give Jane a flex-grow of 3 and Jack a flex-grow of 1, the browser
will share the extra space with a 3:1 ratio.
This means the total value of the extra space becomes 4 (3+1). Jane will then get 3/4 of the
extra space. And Jack will get 1/4 of it.

The extra space is shared proportionately betwee Jane and Jack

Another explanation:

The flex-grow property is a property you define on a flex item and it tells the item how
much of the extra space that item is allowed to take to fill its container. By default this
property is set to 0 which means the item does not get any extra space. Let’s first look at a
flex container where none of the items have flex-grow set.

As you can see each item is taking up only its width and the rest of the space in the
container is unfilled. This is the default behavior of flexbox, but if you want one or more
items to fill the remaining space you need flex-grow.

By setting a flex-grow of 1 we are telling the second element that it should get 1 part of
the extra space and since no other items have a flex grow that 1 part of extra space is the
entirety of the extra space.

.flex-item:nth-child(1),
.flex-item:nth-child(2) {
flex-grow: 1;
}

In this example we set both the first and second element to a flex-grow of 1 so now each of
those element will receive 1 part of the remaining space. To determine how much space
that is we just add up all the flex-grow numbers for each item in the container (1 + 1 = 2)
and then divide the flex-grow of each item by that number. Since our flex-grow for each
item is 1 each item will get 1/2 of the remaining space added to it.

We can make more complex layouts, though, by giving some elements more or less of the
available space.

.flex-item:nth-child(1) {
flex-grow: 2;
}

.flex-item:nth-child(2) {
flex-grow: 1;
}

In this example we are saying the first element should get 2 parts of the remaining space
while the second element only gets 1 part. When we do the math we will see that the first
element gets 2/3 of the remaining space while the second element only gets 1/3 the
remaining space.

At first glance you may think this code is saying that the first element should be twice the
size of the second element but flex grow only cares about the remaining space after all
elements are added to the container. Since by default our 3 elements take up 60% of the
container size the remaining space to divide between the elements is only 40% of the
container size. We can actually modify how this remaining space is calculated, though, by
using flex-basis

The flex-shrink property (Negative Free Space)

If the flex items in a container overflow the container they will automatically shrink down
to fill the correct size. This is because by default flex-shrink is set to 1 on all flex items.

.flex-item {
width: 50%;
}

Even though each element should be 50% of the container they shrink down evenly so that
each element is only 33% of the container size. If we wanted to prevent one of the children
from shrinking we could set the flex-shrink to 0.

.flex-item {
width: 50%;
}

.flex-item:nth-child(1) {
flex-shrink: 0;
}

As you can see the first element stays 50% of the container size and does not shrink while
the other two elements shrink down to ensure all items can fit in the container.
We can also make it so that some items shrink more than other.

.flex-item {
width: 50%;
}

.flex-item:nth-child(1) {
flex-shrink: 2;
}

By setting flex-shrink to 2 we are saying that the first element should lose 2 parts of the
overflown space while the other two elements each only lose 1 part since they are set to
a flex-shrink of 1 by default. This works exactly the same as flex-grow when it comes to
proportions, but flex-shrink deals with the overflown space outside the container
while flex-grow deals with the space left over inside the container.

For the most part this is not really a property that you will have to mess with much since
you usually only care about growing items and the default of shrinking when overflown is
usually what you want.

Also, an important thing to note is that flex-shrink is pretty smart and will ensure that if
you have one really large item and one really small item that they will shrink in a way that
the large item shrinks more so that the small items doesn’t shrink so small that it
disappears.

----------------------------------------------------------------------------------------------------------------------------

In most of the examples we've seen so far, we've had extra space to work with. But what if
our children are too big for their container?

The flex-shrink property is the opposite of flex-grow. It defines how flex items should
behave when there’s not enough space on the screen. This happens when flex items are
larger than the flex container.

You use flex-grow when you want to increase the flex item's size if there's extra space. But,
you use flex-shrink when you want to decrease the flex-item's size if there's not enough
space in the flex container.

Alright, so: we have two children, each with a hypothetical size of 250px. The container
needs to be at least 500px wide to contain these children at their hypothetical size.

Let's suppose we shrink the container to 400px. Well, we can't stuff 500px worth of
content into a 400px bag! We have a deficit of 100px. Our elements will need to give up
100px total, in order for them to fit.

The flex-shrink property lets us decide how that balance is paid.

Like flex-grow, it's a ratio. By default, both children have flex-shrink: 1, and so each child
pays ½ of the balance. They each forfeit 50px, their actual size shrinking from 250px to
200px.

Now, let's suppose we crank that first child up to flex-shrink: 3:


We have a total deficit of 100px. Normally, each child would pay ½, but because we've
tinkered with flex-shrink, the first element winds up paying ¾ (75px), and the second
element pays ¼ (25px).

Note that the absolute values don't matter, it's all about the ratio. If both children
have flex-shrink: 1, each child will pay ½ of the total deficit. If both children are cranked
up to flex-shrink: 1000, each child will pay 1000/2000 of the total deficit. Either way, it
works out to the same thing.

See the example below:

<div class="numbers-container">
<p id="one">1</p>
<p id="two">2</p>
<p id="three">3</p>
<p id="four">4</p>
</div>

.numbers-container {
display: flex;
justify-content: flex-start;
/* Other styles */
}

#one {
flex-shrink: 2;
background-color: #fe4f46;
}
The first card shrinks to make room for the others

In the example, each of the four numbers has a width of 150px (that's a total of 600px).
But the numbers-container has a width of 400px which is not enough.

The cards have to shrink to fit in the available space. But Number 1 which with a flex-
shrink value of 2 shrinks to become twice as small as the other numbers.

What if you don't want a flex item to shrink?

To prevent a flex item from shrinking, give it a flex-shrink value of 0.

For example, when you give Number 1 a flex-shrink of 0, it will maintain the width of
150px. And the other flex items will shrink to fit in the remaining space.

The first card does not shrink because it has a flex-shrink value of 0.

Shrinking and proportions

In the example we've been looking at, both Flex children have the same hypothetical size
(250px). When figuring out how to shrink them, we can calculate it exclusively using flex-
shrink.

As we saw earlier, though, the shrinking algorithm will also try and preserve the
proportions between siblings. If the first child is 2x the size of the second, it will shrink
more aggressively.

So, the full calculation involves looking at each child's relative flex-shrink and its relative
size.

I had an epiphany a while back about flex-shrink: we can think of it as the “inverse” of flex-
grow. They're two sides of the same coin:

 flex-grow controls how the extra space is distributed when the items are smaller than
their container.
 flex-shrink controls how space is removed when the items are bigger than their
container.

This means that only one of these properties can be active at once. If there's extra
space, flex-shrink has no effect, since the items don't need to shrink. And if the children
are too big for their container, flex-grow has no effect, because there's no extra space to
divvy up.

I like to think of it as two separate realms. You're either on Earth, or in the Upside Down?.
Each world has its own rules.
Preventing shrinking

Sometimes, we don't want some of our Flex children to shrink. I notice this all the time
with SVG icons and shapes. Let's look at a simplified example:

When the container gets narrow, our two circles get squashed into gross ovals. What if
we want them to stay circular?

We can do this by setting flex-shrink: 0:

When we set flex-shrink to 0, we essentially “opt out” of the shrinking process


altogether. The Flexbox algorithm will treat flex-basis (or width) as a hard minimum limit.

Here's the full code for this demo, if you're curious:

Flex Shrink ball demo

<style>
body {
background: hsl(210deg, 30%, 12%);
color: hsl(0deg 0% 100%);
}
.wrapper {
display: flex;
gap: 8px;
}
.item {
height: 32px;
border: 2px solid hsl(210deg 8% 50%);
background: hsl(210deg 15% 20%);
}
.item.stretch {
/* Because this item is empty, it has a default hypothetical width of
0px. This isn't realistic, though; in a typical case, there would be content
in here! And so we set a width of 300px to simulate it containing stuff. */
width: 300px;
flex-grow: 1;
border-radius: 16px;
}
.item.ball {
width: 32px;
/* NOTE: We could prevent the circle from squishing into an oval by setting
border-radius: 16px instead. I'm using percentages because it makes for a
better demo. But even with a pixel-based radius, we still need flex-shrink: 0
to prevent the item from shrinking (give it a shot and see the difference!).
*/
border-radius: 50%;
}
/* This is the key property: */
.item.ball {
flex-shrink: 0;
}
</style>

<div class="wrapper">
<div class="item ball"></div>
<div class="item stretch"></div>
<div class="item ball"></div>
</div>

A simpler approach? So, I teach this concept in my course, and every now and then,
someone will wonder why we're going through all the trouble of using flex-shrink when
there's a simpler approach available:

.item.ball {
min-width: 32px;
}

A few years ago, I would have agreed. If we set a minimum width, the item won't be able
to shrink below that point! We're adding a hard constraint, instead of the soft constraint
of width / flex-basis.

I think this is one of those situations where it's easy to confuse “familiar” with “simple”.
You're probably much more comfortable with min-width than flex-shrink, but that doesn't
mean flex-shrink is more complicated!
After a few years of practice, I actually feel like setting flex-shrink: 0 is the more
straightforward / direct solution to this particular problem. Though, min-width still has an
important role to play in the Flexbox algorithm! We'll talk about that next.

The flex-basis property

To put it simply: In a Flex row, flex-basis does the same thing as width. In a Flex
column, flex-basis does the same thing as height.

As we've learned, everything in Flexbox is pegged to the primary/cross axis. For


example, justify-content will distribute the children along the primary axis, and it works
exactly the same way whether the primary axis runs horizontally or vertically.

width and height don't follow this rule, though! width will always affect the horizontal size.
It doesn't suddenly become height when we flip flex-direction from row to column.

And so, the Flexbox authors created a generic “size” property called flex-basis. It's
like width or height, but pegged to the primary axis, like everything else. It allows us to set
the hypothetical size of an element in the primary-axis direction, regardless of whether
that's horizontal or vertical.

You can use the flex-basis property to set the default length of a specific flex item. This is
either the width or height of the item depending on the flex-direction.

If the flex-direction is row or row-reverse, the value for flex-basis becomes the initial width
of the item.

And if flex-direction is column or column-reverse, then the value for flex-basis becomes the
initial height of the item.

Example:

.names-container {
display: flex;
flex-direction: column;
/* Other styles */
}

div {
height: 20px;
}

#jane {
flex-basis: 60px;
}
Example of flex-basis setting the height of an item

In the example, the height for the divs is set at 20px. But Jane gets a flex-basis value of
60px. And that overrides the 20px given to all the divs.

Note: The flex-basis of 60px becomes the height for Jane because the flex
direction is column. This means the main axis is vertical.

Here is another example. This time, the flex-direction is row. This means the flex-basis will
set the width of the item.

.names-container {
display: flex;
flex-direction: row;
/* Other styles */
}

div {
width: 70px;
}

#jane {
flex-basis: 140px;
}

Example of flex-basis setting the width of an item

While all the other divs have a width of 70px, Jane has a width of 140px set by the flex-
basis.

Not exactly the same

In general, we can use width and flex-basis interchangeably in a Flex row, but there are
some exceptions. For example, the width property affects replaced elements like images
differently than flex-basis. Also, width can reduce an item below its minimum size,
while flex-basis can't.

It's well outside the scope of this blog post, but I wanted to mention it, because you may
occasionally run into edge-cases where the two properties have different effects.

The flex Shorthand Property

You can use flex as a shorthand for the flex-grow, flex-shrink, and flex-basis properties.

For example, instead of writing the following:

.flex-item {
flex-grow: 2;
flex-shrink: 0;
flex-basis: 50px;
}

You can use the shorthand like so and it will have the same effect:
.flex-item {
flex: 2 0 50px;
}

The flex property can take up to three values. The order of the values is important. The
browser assigns the first value for flex-grow, the second for flex-shrink, and the third
for flex-basis.

The default values for flex are 1 0 auto.

This means if you give flex a single value of 2, the browser uses 2 for flex-grow. And then it
sets flex-shrink to 0 and flex-basis to auto.

How to Center an Element With Flexbox

One of the headaches for many front-end developers is centering elements. Flexbox has a
perfect solution for that. There are two steps involved.

1. Make the parent element a flex container by setting display to flex.


2. Give a value of center to both justify-content and align-items.

That's it! Your element will be perfectly centered.

Example:

<div class="name-container">
<p>JOHN</p>
</div>
.name-container {
display: flex;
justify-content: center;
align-items: center;
/* Other Styles */
}

Whether you're trying to center text, images, or even an entire navigation bar, this will
work just fine.

Gapping flex items horizontally and vertically

At this point, one major aspect left for your flex container styling is adding gaps to your
flex items. You will want to be able to add equal gaps between flex items either
horizontally, vertically, or on both sides.

You can do this with the gap property. The gap property controls the amount of space
between each flex item. The gap or spacing is only applied between the flex items and not
on the outer edges. This property is for more than just flexbox, as it works in grid and
multi-column layouts.

Example:

.names-container {
display: flex;
flex-wrap: wrap;
gap: 50px 10px;
/* row-gap column-gap */
}
If the gap you want between the rows and the columns is the same, you can use a single
value. The browser will apply the same value to both rows and columns.

Example:

.names-container {
display: flex;
flex-wrap: wrap;
gap: 10px;
/* Other Styles */
}

You can also use the properties row-gap if you need to apply a specific gap value between
only the rows. and column-gap if you need to add gaps between only the columns.

Example: Adding gaps between only the rows:

.names-container {
display: flex;
flex-wrap: wrap;
row-gap: 20px;
/* Other Styles */
}
Example: Adding gaps between only the columns:

.names-container {
display: flex;
flex-wrap: wrap;
column-gap: 20px;
/* Other Styles */
}

Flex shorthand

The flex property is the shorthand for flex-grow, flex-shrink,


and flex-basis combined. The second and third parameters
(flex-shrink and flex-basis) are optional.

It may have several values:

 flex-grow flex-shrink flex-basis: values of the three


properties combined

 none: same as 0 0 auto (makes the flex items fully inflexible)

 initial: same as 0 1 auto (the default value; it is based on


the width and height properties)

 auto: same as 1 1 auto (it is based on the width and height properties, but makes the
flex items fully flexible)

 <positive number>: same as <positive number> 1 0 (makes the flex item flexible and
sets the flex basis to zero)
You can make one item flexible by applying the flex: 1; property and make other ones
static by applying flex: initial; width: 300px; (or another value for the fixed width).

For example, flex: 1 1 300px; is identical to the code below:

flex-grow: 1;
flex-shrink: 1;
flex-basis: 300px;

And flex: 1; is identical to the code below:

flex-grow: 1;
flex-shrink: 1;
flex-basis: 0%;

In the example above, the width of a flex item will not be defined by its content but by the
flex-grow property.

body {
display: flex;
flex-direction: column;
min-height: 100vh;
}

main {
flex: 1;
}

You can use flex with one or two values, according to the following rules and assumptions:

/* One relative value: flex-grow */


flex: 1;
/* One absolute value: flex-basis */
flex: 20rem;
flex: 50px;
/* One relative and one absolute value: flex-grow | flex-basis */
flex: 1 20rem;
/* Two relative values: flex-grow | flex-shrink */
flex: 1 2;
/* Three values: flex-grow | flex-shrink | flex-basis */
flex: 1 2 20rem;
/* Fully inflexible layout: equivalent of flex: 0 0 auto */
flex: none;

place-content

This is the shorthand for the justify-content and align-content properties:

Let's duplicate the results:

Please note that it works on the parent class.

.container{
place-content : center flex-end;
}

Example 1: Creating a Navbar

One common use case for Flexbox is building a responsive navbar. In this example, we will
use the justify-content and align-items properties to align the navbar links horizontally and
vertically within the container. We will also utilize the flex-direction property to control the
layout of the navbar items.

<nav class="navbar">
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Portfolio</a>
<a href="#">Contact</a>
</nav>

.navbar {
display: flex;
flex-direction: column; /* Mobile layout */
}

@media screen and (min-width: 768px) {


.navbar {
flex-direction: row; /* Desktop layout */
justify-content: space-around; /* Horizontal alignment */
}
}

.navbar a {
text-decoration: none;
padding: 10px;
color: #333;
}

Example 2: Building a Pricing Grid

Flexbox excels at creating grid-like layouts. In this example, we will use Flexbox to build a
responsive pricing grid with equal heights for each pricing plan. We will make use of
the flex-direction, flex-wrap, and align-items properties to achieve this layout.

<div class="pricing-grid">
<div class="pricing-plan">
<h2>Basic Plan</h2>
<p>Includes basic features</p>
<span class="price">$10/month</span>
<a href="#" class="btn">Sign Up</a>
</div>
<div class="pricing-plan">
<h2>Pro Plan</h2>
<p>Includes advanced features and support</p>
<span class="price">$20/month</span>
<a href="#" class="btn">Sign Up</a>
</div>
<div class="pricing-plan">
<h2>Premium Plan</h2>
<p>Includes premium features, support, and priority access</p>
<span class="price">$30/month</span>
<a href="#" class="btn">Sign Up</a>
</div>
</div>

/* Create a container for the pricing grid */


.pricing-grid {
display: flex;
justify-content: space-between; /* Distribute space between plans */
max-width: 800px; /* Adjust as needed */
margin: 0 auto; /* Center the grid horizontally */
}

/* Style each pricing plan */


.pricing-plan {
text-align: center;
border: 1px solid #ccc;
padding: 20px;
flex: 1; /* Distribute available space equally among plans */
display: flex;
flex-direction: column; /* Stack content vertically */
}

/* Style pricing details */


.price {
font-size: 24px;
font-weight: bold;
color: #333;
margin-top: auto; /* Push the price to the bottom of the card */
}

/* Style the "Sign Up" button */


.btn {
display: inline-block;
padding: 10px 20px;
background-color: #007BFF;
color: #fff;
text-decoration: none;
border-radius: 5px;
margin-top: 10px;
}

/* Add hover effect to the button */


.btn:hover {
background-color: #0056b3;
}

Example 3: Creating a Flexible Card Layout


Flexbox is perfect for creating flexible card layouts. In this example, we will use Flexbox to
create a responsive card layout with variable card heights. We will employ the flex-
wrap and justify-content properties to ensure that the cards resize and wrap properly on
different screen sizes.

<div class="card-container">
<div class="card">
<h2>Card 1</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
<div class="card">
<h2>Card 2</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed
euismod, diam ut aliquam elementum.</p>
</div>
<div class="card">
<h2>Card 3</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed
euismod, diam ut aliquam elementum, libero enim.</p>
</div>
</div>

.card-container {
display: flex;
flex-wrap: wrap; /* Allow cards to wrap to the next row */
justify-content: space-between; /* Distribute space between cards */
max-width: 800px; /* Adjust as needed */
margin: 0 auto; /* Center the container horizontally */
}

/* Style the individual cards */


.card {
background-color: #f2f2f2;
border: 1px solid #ccc;
padding: 20px;
margin: 10px;
flex: 1 0 calc(33.33% - 20px); /* Calculate width for three cards per row
*/
min-width: 250px; /* Minimum card width */
max-width: 350px; /* Maximum card width */
display: flex;
flex-direction: column;
}

/* Style card content */


.card h2 {
font-size: 18px;
margin-bottom: 10px;
}

.card p {
flex-grow: 1;
margin-bottom: 10px;
}

These examples demonstrate just a fraction of what you can achieve with CSS Flexbox.
The flexibility and versatility of Flexbox make it an essential tool for responsive web design
and creating visually appealing layouts.

You might also like