惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cisco Talos Blog
Cisco Talos Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
爱范儿
爱范儿
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Jina AI
Jina AI
雷峰网
雷峰网
The Register - Security
The Register - Security
The Cloudflare Blog
博客园 - 【当耐特】
M
MIT News - Artificial intelligence
I
InfoQ
博客园 - 三生石上(FineUI控件)
H
Help Net Security
博客园 - 司徒正美
Vercel News
Vercel News
WordPress大学
WordPress大学
S
SegmentFault 最新的问题
云风的 BLOG
云风的 BLOG
B
Blog
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
L
LangChain Blog
人人都是产品经理
人人都是产品经理
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
T
Tailwind CSS Blog
aimingoo的专栏
aimingoo的专栏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Recorded Future
Recorded Future
小众软件
小众软件
Martin Fowler
Martin Fowler
罗磊的独立博客
Stack Overflow Blog
Stack Overflow Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
酷 壳 – CoolShell
酷 壳 – CoolShell
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Apple Machine Learning Research
Apple Machine Learning Research
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - Franky
Hugging Face - Blog
Hugging Face - Blog
Y
Y Combinator Blog
V
Visual Studio Blog
F
Fortinet All Blogs
Microsoft Azure Blog
Microsoft Azure Blog
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
N
Netflix TechBlog - Medium
V
V2EX
Blog — PlanetScale
Blog — PlanetScale

Ahmad Shadeed

Better fluid sizing with round() Use Cases for Field Sizing The Basics of Anchor Positioning Item Flow CSS Relative Colors Balancing Text In CSS Should masonry be part of CSS grid? CSS display contents CSS Grid Areas CSS Cap Unit An Interactive Guide to CSS Container Queries CSS :has() Interactive Guide CSS Nesting UX in DevTools CSS Nesting Future CSS: State Container Queries Rebuilding a comment component with modern CSS Conditional CSS with :has and :nth-last-child CSS Text balancing with text-wrap:balance CSS Masking Do we need CSS flex-wrap detection? My CSS Wishlist Conditional CSS CSS Style Queries Inside the mind of a frontend developer: Article layout Inside the mind of a frontend developer: Hero section CSS container queries are finally here The CSS behind Figma First Look At The CSS object-view-box Property Learn CSS Subgrid CSS :has Parent Selector Aligning Content In Different Wrappers Flexbox Dynamic Line Separator Hello, CSS Cascade Layers Building UI Components With SVG and CSS A Deep CSS Dive Into Radial And Conic Gradients Defensive CSS Building Real-life Components: Facebook Messenger Conditional Border Radius In CSS CSS Container Query Units Less Absolute Positioning With Modern CSS Aligning a Button Label Vertically Comparing Design Mockups To Code Result Using HSL Colors In CSS Custom Scrollbars In CSS Let CSS Container Queries For Designers The State of CSS Cross-Browser Development Overflow Issues In CSS Inspect Element As A Way To Increase Your Curiosity Handling Text Over Images in CSS Digging Into CSS Logical Properties Clipping Scrollable Areas On The inline-start Side Understanding Clip Path in CSS The Art of Building Real-life Components Handling Short And Long Content In CSS CSS Scroll Snap A Deep Dive Into CSS Grid minmax() CSS Variables 101 Finding The Root Cause of a CSS Bug Learn CSS centering How to detect browser support for Flexbox Gap CSS Mistakes While On Autopilot Understanding CSS Multiple Backgrounds Aligning Logo Images in CSS Grid for layout, Flexbox for components Colors in CSS Thinking About The In-between Design Cases min(), max(), and clamp() CSS Functions Image Techniques On The Web Everything About Auto in CSS Learn Box Alignment Let Learn CSS Positioning Intrinsic Sizing In CSS CSS Grid Template Areas In Action Hiding Elements On The Web Creating a Variable Color Font From Scratch Building a Football Ticket With CSS and SVG Blending Modes in CSS CSS Variables With Inline Styles Implementing Dark Mode For My Website Rebuilding Apple Music Header in HTML & CSS Accessible Checkbox Layout Flickering On Browser Resize Enhancing The Clickable Area Size Custom Underlines with SVG Part 3: The Process of Implementing A UI Design From Scratch Part 2: The Process of Implementing A UI Design From Scratch Building An Old Nav Design CSS Flexbox: 5 Real World Use Cases I Used CSS Inline Flex For The First Time The Process of Implementing A UI Design From Scratch Common CSS Issues For Front-End Projects Handling Long and Unexpected Content in CSS How to Build Web Form Layouts With CSS Grid Grid Layout Ah-ha Moment Enhancing Our Components with CSS :empty Building Resizeable Components with Relative CSS Units CSS Writing Mode The Journey of Learning Front End Web Development on a Daily Basis
Digging Into the Flex Property
Ahmad Shadeed · 2020-08-05 · via Ahmad Shadeed

The Layout Maestro

I spent years teaching CSS layout on this blog. I put everything I know into The Layout Maestro course: 70+ lessons and 150+ interactive examples that teach you how to think CSS layouts, not just memorize syntax.

Get the course

Have you ever wondered about how the CSS flex property works? It’s a shorthand for flex-grow, flex-shrink, and flex-basis. The most common use-case I notice on the web is flex: 1, which lets a flex item to expand and fill the available space.

In this article, I will go through the shorthand and the longhand properties in detail, and explain when and why to use them with practical and visual examples.

The flex-grow sets the grow factor which allows a flex item to grow and fill the available space. The value of flex-grow only accepts an integer number. Consider the following.

<div class="wrapper">
  <div class="item item-1"></div>
  <div class="item item-2"></div>
  <div class="item item-3"></div>
</div>
.wrapper {
  display: flex;
  flex-wrap: wrap;
}

.item {
  flex-grow: 1;
}

Note: the flex-grow can affect the width or the height, depending on the flex-direction property. For the following examples, please assume that the flex-direction is set to row (the default value) unless I clarify something else.

Notice that without using flex-grow, the flex items width will default to their initial width. However, with flex-grow: 1 being used, the available space was distributed between them.

You might be wondering, how space is distributed between the flex items? Well, that’s a good question, and I will answer it shortly.

In the figure below, that’s how the items look without flex-grow. In other words, that’s their natural size.

To understand how the flex item width is calculated, see the equation below. I learned about the equation from this post by Samantha Ming (Thank you!).

Let’s calculate the size of the item which contains the text “CSS”.

Item width = ( (flex-grow / total flex-grow) * available space) + initial item width

Flex-grow: the flex grow factor for the item

Total flex-grow: the summation of flex-grow value for all flex items

Available space: before applying flex-grow

Item width: the initial width of the item

---> Item width = ( (1 / 3) * 498) + 77 = 241

Multiple flex-grow factors

In the previous example, the flex-grow value is the same for all flex items. Let’s try to add flex-grow: 2 for the first item. How it will be calculated? Keep in mind that the available space for our example is 498px.

I hope it’s clearer now.

Can we use zero as a value for flex-grow?

Of course! Since the flex-grow property accepts integer values, it’s possible to use 0 as a way to prevent a flex item from taking the available space.

This can be useful in edge cases where we want to force a flex item to stay with its initial width.

Flex grow doesn’t make flex items equal

There is a common misconception that using flex-grow will make the items equal in width. This is incorrect. The idea of using flex-grow is to distribute the available space. As you saw in the equation, the width of each flex item is calculated based on its initial width (The width before applying flex-grow).

If you want to make the flex items equal in width, it’s possible by using flex-basis. I will explain that in the coming sections.

The flex-shrink property

The flex-shrink sets the shrink factor of a flex item. If the size of all flex items is larger than the wrapper, items will shrink according to the flex-shrink factor.

Consider the following example. The middle item has a width of 300px, and with flex-shrink: 1 is set. This will allow the item to shrink in width if there is no space available to fit all flex items.

.item-2 {
  width: 300px;
  flex-shrink: 1;
}

The browser will keep the item width as equal to 300px under the following conditions:

  • The sum of all items width is less than the wrapper width
  • The viewport width is equal or less than the item

Here is how the item behaves with different viewport sizes.

As you see in the figure, the width is 300px until the viewport width is less than 300px.

The flex-basis property

It sets the initial size of the flex item before distributing the free space according to the flex factors. The size can be referred to width by default, and height (in case of flex-direction: column).

The flex-basis property can accept the same values as the width or height properties. The default value is auto, which resolves to content. The content value is an automatic size based on the flex item content size.

.item-1 {
  flex-grow: 0;
  flex-shrink: 0;
  flex-basis: 50%;
}

In the example above, the first item has a width of 50%. It’s important to reset the flex-grow to 0 to prevent the item from becoming larger than 50%.

What will happen if we use 100% instead? The item will take 100% width of its parent, and the other items will wrap into a new line.

.item-1 {
  flex-grow: 0;
  flex-shrink: 0;
  flex-basis: 100%;
}

The flex shorthand property

It’s a shorthand for flex-grow, flex-shrink, and flex-basis. The default value for flex is 0 1 auto. What that means is that it allow flex items to grow based on their content size.

In that context, there is something important that I wanted to highlight, which is absolute and relative flex-items. No, this is not about CSS positioning, it’s about something related to flexbox.

Flex items relative sizing

.item {
  /* Equivalent to flex: 1 1 auto */
  flex: auto;
}

The size of flex items is based on the content. As a result, flex items with more content will be larger.

Flex items absolute sizing

On the contrary, when the flex-basis property is set to 0, all flex items will grow to the same size.

.item {
  /* Equivalent to flex: 1 1 0% */
  flex: 1;
}

What I like about the flex property

From its name, this property is flexible in the values it can take. Take the following examples.

One unitless value

.item {
  flex: 1;
}

If it has only one unitless value, it will be considered as flex-grow, and the longhand values will be 1 1 0.

Two unitless values

.item {
  flex: 1 1;
}

The values are flex-grow and flex-shrink, respectively. The flex-basis will default to 0.

One length value

This will be used for flex-basis. The flex-grow and flex-shrink will default to 1.

.item {
  flex: 100px;
  /* flex: 1 1 100px */
}

Using a unitless 0

In cases where you need to set the flex-basis to zero by using the flex shorthand.

.item {
  flex: 0;
}

This is not recommended as it will confuse both of the developer and the browser. How can you decide if that 0 is for the flex factors (grow or shrink) or for the flex-basis? It’s confusing. According to the CSS spec:

A unitless zero that is not already preceded by two flex factors must be interpreted as a flex factor. To avoid misinterpretation or invalid declarations, authors must specify a zero <‘flex-basis’> component with a unit or precede it by two flex factors.

Instead, you should append a unit like px or %.

.item {
  flex: 0%;
  /* flex: 1 1 0% */
}

When you need to set the grow, shrink, and basis, it’s better to use the flex property for that purpose.

According to the CSS spec:

Authors are encouraged to control flexibility using the flex shorthand rather than with its longhand properties directly, as the shorthand correctly resets any unspecified components to accommodate common uses.

Use Cases

User avatar

A common use-case for flexbox is for a user component. The avatar and the text content should be on the same line.

<div class="user">
  <img class="user__avatar" src="shadeed.jpg" alt="" />
  <div>
    <h3>Ahmad Shadeed</h3>
    <p>Author of Debugging CSS</p>
  </div>
</div>
.user {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.user__avatar {
  flex: 0 0 70px;
  width: 70px;
  height: 70px;
}

Notice that I added flex: 0 0 70px for the avatar. It’s important to use it as some old browser might look the image look compressed, if flex is not set. Adding on that, flex has a higher priority than the width property (in case of flex-direction: row) or height (in case of flex-direction: column).

If we change the avatar size by only tweaking the flex property, the width will be ignored by the browser.

.user__avatar {
  /* The width is 100px, not 70px */
  flex: 0 0 100px;
  width: 70px;
  height: 70px;
}

You have a title for a section header, and it should fill all the available space. Using flex: 1 is perfect for that case.

.page-header {
  display: flex;
  flex-wrap: wrap;
}

.page-header__title {
  flex: 1;
}

Send message input

This is very common in messaging apps, like Facebook messenger or Twitter. The input should fill the available space, with a fixed width for the send button.

form {
  display: flex;
  flex-wrap: wrap;
}

input {
  flex: 1;
  /* Other styles */
}

The above examples are useful use-cases for flex-grow. However, some cases are ignored or not mentioned at all in some of the flex articles out there. Let’s explore them!

Aligning the last item across two cards

Let’s suppose that CSS grid is being having a two-column layout. The issue is that the dates are not aligned. They should be at the same line (The red one).

We can do that with flexbox.

<div class="card">
  <img src="thumb.jpg" alt="" />
  <h3 class="card__title">Title short</h3>
  <time class="card__date"></time>
</div>

By setting the flex-direction: column, we can use flex-grow on the title to make it fill the available space, and thus keeping the date at the end, even if the title is short.

.card {
  display: flex;
  flex-direction: column;
}

/* First solution */
.card__title {
  flex-grow: 1;
}

Also, this possible without using flex-grow. Thanks to auto margins and flexbox! I wrote a detailed article about auto in CSS, if you want to dig into more details.

/* Second solution */
.card__date {
  margin-top: auto;
}

Use Cases - More than one flex factor

What I mean here is using flex-grow or flex-shrink, but with a value other than 1. In this section, I will explore some ideas where we can incorporate that.

Inspired by Facebook (I stealed the icons, too), this actions footer has four items, and the last one has a smaller width. What we can do is the following:

.actions {
  display: flex;
  flex-wrap: wrap;
}

.actions__item {
  flex: 2;
}

.actions__item.user {
  flex: 1;
}

Expand animation

An interesting thing we can do is to animate a flex item on hover. This can be extremely useful. Here is a simple example of what’s possible:

.palette {
  display: flex;
  flex-wrap: wrap;
}

.palette__item {
  flex: 1;
  transition: flex 0.3s ease-out;
}

.palette__item:hover {
  flex: 4;
}

Expanding a pricing plan

I love this demo on Codepen. Once a card is activated, it expands by changing flex-grow to 4.

See the Pen 🔘 Flexbox Toggles 🔘 by Shaw (@shshaw) on CodePen.

When the content is larger than its wrapper

A while ago, I got an email from a reader asking about an issue he is facing. As in the figure, we have two images that should stay within the boundaries of their wrapper.

.wrapper {
  display: flex;
}

.wrapper img {
  flex: 1;
}

However, even with flex: 1, the images are still overflowing the wrapper. According to the CSS spec:

By default, flex items won’t shrink below their minimum content size (the length of the longest word or fixed-size element). To change this, set the min-width or min-height property.

In our case, the images are too large, and flexbox won’t shrink them to fit the wrapper. To change this behaviour, we need to set the following:

.wrapper img {
  flex: 1;
  min-width: 0;
}

I explained about this issue in my article about min and max width/height in CSS.

Conclusion

That’s all. I explained the basics of flex longhand properties, and how to use them. I hope you learned something new from this article. Do you have a comment or a suggestion? Please feel free to ping me on @shadeed9.

Thank you for reading.

I’m writing an ebook

I’m excited to let you know that I’m writing an ebook about Debugging CSS.

If you’re interested, head over to debuggingcss.com and subscribe for updates about the book.

{% include share.html text = “Digging Into the Flex Property” link = “https://ishadeed.com/article/css-flex-property/” %}

Resources and Further Reading

Credit

  • Color palette from coolors.co