flexbox:1.0.0

This article will cover all the fundamental concepts you need to get good with the CSS Flexbox model. It’s a long one, so I hope you’re ready for it.

本文将介绍您熟悉CSS Flexbox模型所需的所有基本概念。 这是一个很长的时间,所以希望您已经做好准备。

If you prefer to read the entire tutorial in a single .pdf document, here’s the download link — no strings attached, & if you want a more immersive experience, use the interactive course — it is free. No strings attached.

如果您希望在一个.pdf文档中阅读整个教程,请访问以下下载链接 -不附带任何条件;如果您想获得更身临其境的体验,请使用交互式课程 -免费。 没有任何附加条件。

关于Flexbox学习曲线的说明 (A note on Flexbox’s learning curve)

Here’s a tweet from Philip Roberts, a developer whom I respect very much:

这是菲利普·罗伯茨(Philip Roberts)的一条推文,我非常尊重他:

Learning Flexbox may not be fun at first. It will challenge what you know about layouts in CSS. But that’s fine. Everything worth learning begins that way.

刚开始学习Flexbox可能不会很有趣。 它将挑战您对CSS布局的了解。 但这很好。 一切值得学习的方式都从这种方式开始。

Flexbox is certainly something you should take seriously. It paves the way for the modern style of laying out content, and it’s not going away anytime soon. It has emerged as a new standard. So with outstretched arms, embrace it!

Flexbox当然是您应该认真对待的事情。 它为布局内容的现代风格铺平了道路,并且不会很快消失。 它已成为一种新标准。 因此,张开双臂拥抱它!

您将学到什么 (What you’ll learn)

I’ll first walk you through the basics of Flexbox. I believe any attempt at understanding Flexbox must begin here.

我将首先向您介绍Flexbox的基础知识。 我相信任何了解Flexbox的尝试都必须从这里开始。

Learning the fundamentals is cool. What’s even cooler is applying these fundamentals to build real-world apps.

学习基础知识很酷。 更酷的是应用这些基础知识来构建实际的应用程序。

I’ll walk you through building a lot of “small things.” Afterwards, I’ll wrap things up with this music app completely laid out with Flexbox.

我将引导您完成许多“小事情”。 之后,我将用完全由Flexbox布局的音乐应用程序来完成所有工作。

Doesn’t that look pretty?

看起来不漂亮吗?

I’ll get into the inner workings of Flexbox while you learn to build the music app layout. You’ll also get a feel for the role Flexbox plays in responsive web design, too.

当您学习构建音乐应用程序布局时,我将介绍Flexbox的内部工作原理。 您还将了解Flexbox在响应式Web设计中的作用。

I’m excited to show you all this.

很高兴向您展示所有这些。

But before you get started building user interfaces, I’m going to walk you through some drills, first. This may seem boring, but it’s all part of the process of getting you adept at Flexbox.

但是,在开始构建用户界面之前,我将首先指导您完成一些练习。 这看起来很无聊,但这是让您精通Flexbox的全部过程。

Let’s get started.

让我们开始吧。

介绍 (Introduction)

CSS has evolved a lot over the past few years. Designers loved the introduction of filters, transitions, and transforms. But something was missing. Something we all craved.

CSS在过去几年中发展了很多。 设计师喜欢引入过滤器,过渡和转换。 但是缺少了一些东西。 我们都渴望的东西。

Crafting Intelligent page layouts with CSS seemed to have persisted for too long, and this got many of us writing hacky CSS.

用CSS编写智能页面布局似乎已经持续了太长时间,这使我们许多人编写了拙劣CSS。

We always had to deal with floats, table display hacks, and the consequences they brought. If you’ve written CSS for sometime, you can probably relate to this. And if not, welcome to a better world!

我们总是不得不处理花车,桌子上的桌子乱码以及它们带来的后果。 如果您有一段时间写过CSS,则可能与此有关。 如果没有,欢迎来到一个更美好的世界!

It seems like our prayers as designers and front-end developers have finally been heard. This time, in grand style.

似乎终于听到了我们作为设计师和前端开发人员的祈祷。 这次,气势恢宏。

Now we can all ditch those hacky CSS tricks. No more incessant use of floats, table-cell displays.

现在我们都可以放弃那些骇人听闻CSS技巧。 不再过多使用浮点数,表格单元格显示。

It’s time to embrace a cleaner modern syntax for crafting intelligent layouts. Welcome the CSS Flexbox model.

现在该采用更简洁的现代语法来制作智能布局了。 欢迎使用CSS Flexbox模型。

什么是Flexbox? (What Is Flexbox?)

According to the specification, the Flexbox model provides for an efficient way to layout, align, and distribute space among elements within your document — even when the viewport and the size of your elements is dynamic or unknown.

根据规范,Flexbox模型提供了一种有效的方式来布局,对齐和分配文档中元素之间的空间,即使视口和元素的大小是动态的还是未知的。

If that sounds too formal, I understand the feeling. In just a bit, I’ll explain what that means in plain English.

如果听起来太正式,我理解这种感觉。 稍后,我将用通俗的英语解释这意味着什么。

Whether you write CSS in your dreams, or you’re just getting started, you’ll feel right at home.

无论您是在梦想中编写CSS,还是刚刚开始,都将感到宾至如归。

如何开始使用Flexbox模型? (How do I start using the Flexbox model?)

This is the first question everyone asks, and the answer is much simpler than you may have expected.

这是每个人都提出的第一个问题,答案比您预期的要简单得多。

To start using the Flexbox model, all you need to do is first define a flex-container.

要开始使用Flexbox模型,您需要做的就是首先定义一个Flex容器。

In regular HTML, laying out a simple list of items takes this form:

在常规HTML中,布局简单的项目列表采用以下形式:

<ul> <!--parent element-->  <li></li> <!--first child element-->  <li></li> <!--second child element-->  <li></li> <!--third child element--></ul>

If you glanced at that, you must have seen that the unordered list (ul) houses the list elements(li).

如果您看了一眼,您肯定已经看到无序列表( ul )容纳了列表元素( li )。

You’d call the ul the parent element, and the li the child element.

您将ul称为元素,而li称为元素。

To use the Flexbox model, you must make a parent element a flex container (AKA flexible container).

要使用Flexbox模型,必须使父元素成为flex容器(AKA flexible container )。

You do this by setting display: flex or display: inline-flex for the inline variation. It's that simple, and from there you're all set to use the Flexbox model.

您可以通过设置display: flexdisplay: inline-flex来实现内联变化。 就是这么简单,然后您就可以使用Flexbox模型了。

What actually happens is, a Flexbox formatting context is immediately initiated.

实际发生的是,立即启动了Flexbox格式化上下文。

Told you it wasn't as difficult as you expected.

告诉您,它并不像您预期​​的那么难。

Using an unordered list and a bunch of list elements, below is what initiating a Flexbox formatting context looks like.

使用无序列表和一堆列表元素,下面是启动Flexbox格式化上下文的样子。

/*Make parent element a flex container*/ul {  display: flex; /*or inline-flex*/}

Style the list items just a bit, so you may see what’s going on here.

对列表项进行样式设置,因此您可能会看到这里发生了什么。

li {  width: 100px;  height: 100px;  background-color: #8cacea;  margin: 8px;}

Here is what you should have:

这是您应该拥有的:

You may not have noticed, but something has happened already. The Flexbox formatting context is now initiated.

您可能没有注意到,但是已经发生了一些事情。 现在将启动Flexbox格式化上下文。

Remember that ‘li’ elements are by nature block elements, which means they stack vertically, and this applies for other CSS block elements, such as ‘div’.

请记住,“ li”元素本质上是块元素,这意味着它们是垂直堆叠的,这适用于其他CSS块元素,例如“ div”。

The image above is the result you may have hoped for.

上面的图像是您可能希望得到的结果。

However, with the inclusion of that simple one-liner, display:flex, you can immediately see a change in layout.

但是,通过包含简单的一线display:flex ,您可以立即看到布局的变化。

The list elements are now stacked horizontally, from left to right. Just like they would if you used float.

现在,列表元素从左到右水平堆叠。 就像您使用float一样。

The Flexbox model kicks in as soon as you introduce the “flex display” on any parent element.

一旦在任何父元素上引入“ flex display” ,就会启动Flexbox模型。

You may not understand why that change in the orientation of the list elements came to be. I promise I’ll go into the inner workings of that very soon. For now, blind trust would suffice.

您可能不明白为什么列表元素的方向发生了这种变化。 我保证我很快就会进入内部工作。 就目前而言,盲目信任就足够了。

Understanding that the inclusion of the “flex display” starts off the Flexbox model.

了解“ flex display”的加入是从Flexbox模型开始的。

There’s one more thing I need to call your attention to.

我还需要提醒您一件事。

As soon as you set the display property to flex, the unordered list automatically becomes the flex container and the child elements (in this case, the list elements li) become flex items.

一旦将display属性设置为flex,无序列表将自动成为flex容器 ,子元素(在这种情况下为list元素li )将成为flex项目

These terms would come up over and over again as I walk you through some more interesting things the Flexbox model has in place.

这些术语会一遍又一遍地出现,当我向您介绍Flexbox模型中一些更有趣的东西时。

I’ve used two key words, and I’d like to lay more emphasis on them. They are vital to understanding what lies ahead.

我使用了两个关键词,我想更加强调它们。 他们对于了解未来将至关重要。

  1. Flex container : The parent element you’ve set display: flex on.

    Flex容器 :您设置的父元素display: flex on。

  2. Flex items : The children elements within a Flex container.

    Flex项目 :Flex容器中的子元素。

This is the foundation for using the Flexbox model.

这是使用Flexbox模型的基础。

Flex容器属性 (The Flex Container Properties)

Flex-direction || Flex-wrap || Flex-flow || Justify-content || Align-items || Align-content

Flex-direction || Flex-wrap || Flex-flow || Justify-content || Align-items || Align-content

In the section above, I established some fundamental principles. What flex-containers and flex-items are, and how to initiate the Flexbox model.

在以上部分中,我建立了一些基本原则。 什么是弹性容器和弹性项目,以及如何启动Flexbox模型。

Now is a good time to put all of that to good use.

现在是充分利用所有这些的好时机。

Having set a parent element as a flex container, a couple of alignment properties are made available to be used on the flex container.

将父元素设置为flex容器后,可以使用几个对齐属性以在flex容器上使用。

Just like you’d define the width property on a block element as width: 200px, there are 6 different properties the flex container can take on.

就像您将block元素的width属性定义为width: 200px ,flex容器可以采用6种不同的属性。

The good news is that defining these properties doesn’t require a different approach from what you’re already used to.

好消息是,定义这些属性不需要使用与您已经习惯的方法不同的方法。

1.伸缩方向 (1. Flex-direction)

The Flex-direction property controls the direction in which the flex-items are laid along the main axis.

Flex-direction属性控制柔性项目沿主轴放置的方向

It may take any of four values.

它可以采用四个值中的任何一个。

/*where ul represents a flex container*/ul {  flex-direction: row || column || row-reverse || column-reverse;  }

In layman’s terms, the flex-direction property let's you decide how the flex items are laid out. Either horizontally, vertically or reversed in both directions.

用外行的话来说, flex-direction属性让您决定弹性项目的布局方式。 水平垂直或双向反转

Technically, “horizontal” and “vertical” isn't what the directions are called in the "flex world".

从技术上讲,“ 水平 ”和“ 垂直 ”并不是“柔性世界”中所谓的方向。

These are described as main-axis and cross axis. The defaults are shown below.

这些被描述为主轴交叉轴。 默认值如下所示。

In layman’s terms again, the main-axis’ default direction feels like “horizontal.” From left to right.

再次用外行的话来说,主轴的默认方向就像“ 水平”。 “ 从左到右。

The cross-axis feels like “vertical.” From top to bottom.

横轴的感觉就像“ 垂直。 “ 从上到下。

By default, the flex-direction property is set to row and it aligns the flex-item(s) along the main axis. This explains what happened with the unordered list at the start of this article.

默认情况下, flex-direction属性设置为row ,并且使flex-item沿着主轴对齐。 这说明了本文开头对无序列表的处理方式。

Even though the flex-direction property wasn't explicitly set, it took on the default value of row.

即使未明确设置flex-direction属性,它仍采用row.的默认值row.

The flex items were then laid across the main-axis, stacking horizontally from left to right.

然后,将弹性项目横穿主轴放置,从左到右水平堆叠。

If the flex-direction property is changed to column, the flex-items will be aligned along the cross axis.

如果flex-direction属性更改为column,则flex-items将沿横轴对齐。

They would stack from top to bottom, not from left to right any longer.

它们将从上到下堆叠,不再从左到右堆叠。

2.软包装 (2. Flex-wrap)

The flex-wrap property can take on any of three values:

flex-wrap属性可以采用以下三个值之一:

//where ul represents a flex containerul {  flex-wrap: wrap || nowrap || wrap-reverse;  }

I’ll explain how the flex-wrap property works by walking you through an example.

我将通过一个示例来解释flex-wrap属性的工作方式。

Try sticking a lot more list items into the unordered list.

尝试将更多列表项粘贴到无序列表中。

What do you think? Will the flex container resize to accommodate more, or will it break up the list items unto another line?

你怎么看? flex容器是否会调整大小以容纳更多内容,还是将列表项分解到另一行?

/*adding 3 more li elements*/<ul> <!--parent element-->  <li></li> <!--first child element-->  <li></li> <!--second child element-->  <li></li> <!--third child element-->  <li></li>  <li></li>  <li></li></ul>

Fortunately, the flex-container adapts to accommodate the new flex-items

幸运的是,弹性容器可以适应新的弹性项目

Go a bit further.

再走一点。

Add a ridiculous amount of flex-items to the parent element. Make it a total of 10 items.

向父元素添加大量的flex-items。 总共使10件。

What happens?

怎么了?

Again, the flex container adapts to fit all children in, even if the browser needs to be scrolled horizontally.

同样,即使浏览器需要水平滚动,flex容器也可以适应所有子级。

This is the default behavior of every flex container. A flex container will keep on accommodating more flex items on a single line.

这是每个flex容器的默认行为。 一个伸缩容器将继续在一行上容纳更多伸缩项目。

This is because the flex-wrap property defaults to nowrap. This causes the flex container to NOT wrap.

这是因为flex-wrap属性默认为nowrap 。 这将导致flex容器无法包装。

ul {    flex-wrap: nowrap;     /*Keep on taking more flex items without breaking (wrapping)*/}

The no-wrap isn’t a iron-clad value. It can be changed.

no-wrap不是铁定的价值。 可以更改。

With that number of flex-items, you certainly want the flex-items to “wrap” within the flex-container.

有了这么多的弹性项目,您当然希望弹性项目能够“ 包裹”在弹性容器中。

“Wrap” is a fancy word to say, “when the available space within the flex-container can no longer house the flex-items in their default widths, break unto multiple lines.

“包装”是一个奇特的说法,“当柔性容器中的可用空间无法再以默认宽度容纳柔性项目时,分成多行。

This is possible with the wrapvalue.

使用wrap值可以做到这一点。

ul {    flex-wrap: wrap;}

With this, the flex-items now break up into multiple lines when needed.

这样,弹性项目现在可以在需要时分成多行。

In this case, when a single line can no longer contain all the list items in their default width, they break up into multiple lines. Even on resizing the browser.

在这种情况下,当一行不能再包含其默认宽度的所有列表项时,它们将分成多行。 即使调整浏览器的大小。

Here’s what that looks like.

看起来像这样。

Note that the flex items are now displayed in their default widths. There’s no need to force multiple flex items unto one line.

请注意,弹性项目现在以其默认宽度显示。 无需将多个弹性项目强制设置为一行。

There’s one more value, wrap-reverse.

还有一个值, wrap-reverse

Yes, you guessed right. It lets the flex items break unto multiple lines, but in the reverse direction.

是的,你猜对了。 它使flex项分解为多行,但方向相反。

3.柔性流 (3. Flex-flow)

The flex-flow is a shorthand property which takes flex-direction and Flex-wrap values.

flex-flow是一种速记属性,它采用flex-directionFlex-wrap值。

Ever used the border shorthand property? border: 1px solid red.

曾经使用过border速记财产吗? border: 1px solid red

It's the same concept here. Multiple values declared in one line.

这里是相同的概念。 一行中声明了多个值。

See the example below.

请参见下面的示例。

ul {    flex-flow: row wrap; /*direction "row" and yes, please wrap the items.*/}

Try out the other combinations this could take. flex-flow: row nowrap, flex-flow: column wrap, flex-flow: column nowrap

试用这可能需要的其他组合。 flex-flow: row nowrapflex-flow: column wrapflex-flow: column nowrap

The results produced are not different from what you’ve seen with the flex-direction and flex-wrap values.

产生的结果与您在flex-directionflex-wrap值中看到的没什么不同。

I'm sure you understand what those would produce.

我确定您了解这些会产生什么。

Give them a try.

试试看。

4.证明内容合理 (4. Justify-content)

Life’s really good with the Flexbox model. If you still doubt that, the justify-content property may convince you.

Flexbox模型的生活真的很好。 如果您仍然对此表示怀疑,那么justify-content属性可能会说服您。

The justify-content property takes on any of the 5 values below.

justify-content属性采用以下5个值中的任何一个。

ul {    justify-content: flex-start || flex-end || center || space-between || space-around}

And what exactly does the justify content property bring to the table?

justify content属性到底能带来什么?

Well, It may remind you of the text-align property.

好吧,它可能使您想起text-align属性。

The justify content property defines how flex items are laid out on the main axis.

证明内容属性定义了弹性项目在主轴上的布局方式。

A quick example.

一个简单的例子。

Consider the simple unordered list below.

考虑下面的简单无序列表。

<ul>  <li>1</li>  <li>2</li>  <li>3</li></ul>

Add up some basic styling.

添加一些基本样式。

ul {    border: 1px solid red;    padding: 0;    list-style: none;    background-color: #e8e8e9;  }
li {      background-color: #8cacea;      width: 100px;      height: 100px;      margin: 8px;      padding: 4px;  }

You should have this:

你应该有这个:

With the justify-content property, the three flex-items may be aligned across the main-axis in whatever way you desire.

使用justify-content property ,可以按照您希望的方式在主轴上对齐三个弹性项目。

Here's the breakdown of what's possible.

这是可能的细分。

(i)弹性启动 ((i) Flex-start)

The default value is flex-start.

默认值为flex-start

flex-start groups all flex-items to the start of the main axis.

flex-start将所有flex-item分组到主轴的起点

ul {    justify-content: flex-start;  }

(ii)弹性端 ((ii) Flex-end)

flex-end groups the flex-items to the end of the main axis.

flex-end将flex-item分组到主轴的末端

ul {    justify-content: flex-end;  }

(iii)中心 ((iii) Center)

Center does just what you'd expect: it centers the flex items along the main axis.

Center可以满足您的期望:将flex项沿主轴居中。

ul {    justify-content: center;  }

(iv)间隔 ((iv) Space-between)

Space-between keeps the same space between each flex item.

Space-between间距在每个弹性项目Space-between保持相同的间距。

ul {    justify-content: space-between;  }

Um, did you notice anything different here?

嗯,你注意到这里有什么不同吗?

Take a look at the descriptive image below.

看看下面的描述性图像。

(v)环绕 ((v) Space-around)

Finally, space-around keeps the same spacing around flex items.

最后, space-around空格在弹性项目之间保持相同的间距。

ul {    justify-content: space-around;  }

A second look doesn’t hurt.

再看一次也没有伤害。

See the descriptive image below.

请参阅下面的描述性图像。

Don’t worry if these seem like too much to get a hold of. With a bit of practice you will get very comfortable with the syntax.

不要担心这些东西似乎太多了。 经过一些练习,您将对语法感到非常满意。

Be sure to understand how they affect the display of flex items along the main axis.

确保了解它们如何影响弹性项目沿主轴的显示。

5.对齐项目 (5. Align-items)

The align-items property is somewhat similar to the justify-content property.

align-items属性有点类似于justify-content属性。

Having understood the justify-content property, this should be easier to take in.

了解了justify-content属性后,应该会更容易接受。

Align-items can be set to any of these values: flex-start || flex-end || center || stretch || baseline

可以将flex-start || flex-end || center || stretch || baseline Align-items设置为以下任意值: flex-start || flex-end || center || stretch || baseline flex-start || flex-end || center || stretch || baseline

/*ul represents any flex container*/ul {    align-items: flex-start || flex-end || center || stretch || baseline}

It defines how flex-items are laid out on the cross axis. This is the difference between the align-items property and justify-content.

它定义了弹性项在横轴上的布局方式。 这是align-items属性和justify-content之间的区别。

Below is how the different values affect flex items.

以下是不同的值如何影响弹性项目。

Do not forget the direction being affected by these properties. The cross-axis.

不要忘记方向受这些属性的影响。 横轴。

(i)伸展 ((i) Stretch)

The default value is stretch. This will “stretch” the flex-items so they fill the entire height of the flex container.

默认值为stretch. 这将“ 拉伸”弹性项目,以便它们填充弹性容器的整个高度。

(ii)弹性启动 ((ii) Flex-start)

The flex-start does what you expect. It groups the flex items to the start of the cross-axis.

flex-start可以满足您的期望。 它将弹性项目组合到横轴的起点。

(iii)弹性端 ((iii) Flex-end)

As expected, flex-end groups the flex items to the end of the cross-axis.

如预期的那样, flex-end将flex项目分组到横轴的末端。

(iv)中心 ((iv) Center)

The center value is equally predictable. It aligns the flex items to the center of the flex-container.

center值同样可以预测。 它将弹性项目与弹性容器的中心对齐。

(v)基准 ((v) Baseline)

And the baseline value?

和基线值?

It aligns flex-items along their baselines.

它将弹性项目沿其基线对齐。

Baseline” really sounds fancy.

基准 ”确实听起来很花哨。

The result appears to look just like flex-start but it is subtly different.

结果看起来像flex-start但是有细微的差别。

What the heck is “baseline”?

什么是“基准”?

The image below should help.

下图应该有所帮助。

Notice how all the flex-items are aligned to have their content seat on the “baseline”?

注意所有弹性项目如何对齐以使其内容位于“基线”上?

6.内容一致 (6. Align-content)

While discussing the wrap property, do you remember what happened when you added more flex-items to the flex-container?

在讨论wrap属性时,您还记得在flex容器中添加更多flex项目时会发生什么情况吗?

You got a multi-line flex container.

您有一个多行 flex容器。

The align-content property is used on multi-line flex-containers.

align-content属性用于多行挠性容器。

It takes the same values as align-items apart from baseline.

baseline外,它的取值与align-items相同。

By definition, it controls how the flex-items are aligned in a multi-line flex container.

根据定义,它控制在多行flex容器中如何对齐flex-items。

Just like align-items, the default value is also stretch

就像align-items ,默认值也是stretch

These are values you should now be familiar with. So, here’s how they affect a multi-line flex-container with 10 flex-items.

这些是您现在应该熟悉的值。 因此,这就是它们如何影响具有10个flex-items的多行 flex-container。

(i)伸展 ((i) Stretch)

With stretch, the flex items are “stretched” to fit the available space along the cross-axis.

使用stretch ,可将弹性项目“拉伸”以适应横轴上的可用空间。

The spacing you see between the flex items below is owing to the margin set on the items.

您在下面的弹性项目之间看到的间距是由于在项目上设置的margin所致。

(ii)弹性启动 ((ii) Flex-start)

You’ve seen the flex-start value before.

您之前已经看过flex-start值。

This time it aligns the items in the multi-line container to the start of the cross-axis.

这次,它将多行容器中的项目与横轴的起点对齐。

Remember the default cross axis is from top-to-down.

请记住,默认的交叉轴是从上到下。

Thus, the flex items are aligned to the top of the flex container.

因此,柔性物品对准柔性容器的顶部。

(iii)弹性端 ((iii) Flex-end)

The flex-end value aligns the flex items to the end of the cross-axis.

flex-end值将flex项目与横轴的末端对齐。

(iv)中心 ((iv) Center)

Like you may have guessed, center aligns the flex-items to the center of the cross-axis.

就像你可能已经猜到了, center对齐柔性项的十字轴的中心

That’s the last of the flex-container properties.

这是flex容器属性的最后一个。

You now understand how to use the various flex-container properties.

现在,您了解了如何使用各种flex容器属性。

You’ll use these to work through the practical sections coming up.

您将使用它们来完成接下来的实际部分。

弹性项目属性 (The Flex Item Properties)

Order || Flex-grow || Flex-shrink || Flex-basis

Order || Flex-grow || Flex-shrink || Flex-basis

In the previous section, I explained flex-containers and their alignment properties.

在上一节中,我解释了伸缩容器及其对齐属性。

Beautiful indeed.

确实美丽。

Sure you’re getting a feel of what lies ahead.

当然,您会感觉到前方的一切。

I’d take my focus off flex-containers now, and walk you through flex-items and their alignment properties.

现在,我将注意力从柔韧性容器上移开,并带您逐步了解柔韧性项目及其对齐属性。

Like flex-containers, a couple alignment properties are also made available on all flex-items, too.

像弹性容器一样,所有弹性项目也都具有一对对齐属性。

Let me walk you through them.

让我一窥你。

1.订购 (1. Order)

The order property allows for reordering the flex items within a container.

order属性允许对容器内的flex项目进行重新排序。

Basically, with the order property you can move a flex-item from one position to another. Just like you would do with “sortable” lists.

基本上,可以使用order属性将弹性项目从一个位置移动到另一个位置。 就像您要处理“可排序”列表一样。

This is done without affecting the source code. Which means the position of the flex items in the HTML source code isn’t changed.

这样做不会影响源代码。 这意味着flex项在HTML源代码中的位置未更改。

The default value for the order property is 0. It may take on either negative or positive values.

order属性的默认值为0。它可以采用负值或正值。

It’s worth noting that flex items are re-ordered based on the number values of the order property. From lowest to highest.

值得注意的是,弹性商品是根据order属性的数字值重新排序的。 从最低到最高。

An example always does the trick. Consider the unordered list below:

一个例子总能解决问题。 考虑下面的无序列表:

<ul>    <li>1</li>    <li>2</li>    <li>3</li>    <li>4</li>                          </ul>

By default, the flex items all have an order value of 0.

默认情况下,弹性商品的order值均为0

Just as you expected, you get this (see below) after some basic styling.

正如您所期望的,经过一些基本的样式设置后,您将获得此效果(请参见下文)。

The Flex items are displayed just as specified in the HTML source order. Flex item 1, then 2, 3, and 4.

Flex项目的显示与HTML源顺序中指定的一样。 弯曲项目1,然后2,2,3和4。

What if for some reason you wanted the flex-item 1 to appear last? Without changing the source order in the HTML document?

如果出于某种原因您希望弹性项目1出现在最后怎么办? 无需更改HTML文档中的源顺序?

Without changing the source order” means you do not get to do this:

不更改源顺序 ”意味着您无法这样做:

<ul>    <li>2</li>    <li>3</li>    <li>4</li>    <li>1</li>                      </ul>

Now that’s where the order property comes in.

现在,这是order属性的来源。

All you need to do is make the order value of flex-item 1 higher than that of other list items.

您需要做的就是使flex-item 1的order价值高于其他列表项目的order价值。

If you ever used the z-index property on block elements, you'd be familiar with this sort of thing.

如果您曾经在块元素上使用过z-index属性,您会很熟悉这种事情。

/*select first li element within the ul */    li:nth-child(1) {        order: 1; /*give it a value higher than 0*/    }

The flex items are then re-ordered from lowest to highest.

然后,将弹性项目从最低到最高重新排序。

Do not forget that by default, list-items 2, 3, and 4 all have the order value of 0.

不要忘记默认情况下,列表项2、3和4的顺序值均为0。

Now, flex-item 1 has an order value of 1.

现在,弹性项目1的订单值为1。

Flex-items 2, 3, and 4 all have an order value of 0. So, the HTML source order is kept — no modifications made to the default display.

弹性项目2、3和4的顺序值均为0。因此,保留了HTML源顺序-无需对默认显示进行任何修改。

What if you gave flex-item 2 an order value of 2?

如果给flex-item 2订单值2怎么办?

Yes, you guessed right. It goes up the stack too. It now represents the flex-item with the highest order value.

是的,你猜对了。 它也在堆栈上。 现在,它表示具有最高order值的弹性项目。

And what happens when two flex items have the same order value?

当两个弹性商品具有相同的订单值时会发生什么?

In the example below, flex-item 1 and 3 are given the same order values

在下面的示例中,弹性项目1和3被赋予相同的order

li:nth-child(1) {        order: 1;    }
li:nth-child(3) {        order: 1;    }

The items are still arranged from lowest to highest order value.

物品仍按从最低到最高的顺序排列。

This time, flex-item 3 appears last because it comes after flex-item 1 in the source file (HTML document).

这次,弹性项目3出现在最后,因为它在源文件(HTML文档)中的弹性项目1之后。

The re-ordering is based on the positions in the source file, when two or more flex items have the same order value.

当两个或更多弹性项目具有相同的订购值时,重新排序基于源文件中的位置。

That was a lot of explanation.

那是很多解释。

I’d move on to some other property.

我将继续其他财产。

2.弯曲生长和弯曲收缩 (2. Flex-grow and flex-shrink)

The beauty of flex items is being “flexible.”

弹性物品的美在于“弹性”。

The flex-grow and flex-shrink properties allow us play around this “flexibility” even more.

flex-growflex-shrink属性使我们可以更多地利用这种“ 灵活性”

The flex-grow and flex-shrink properties control how much a flex-item should “grow” (extend) if there are extra spaces, or “shrink” if there are no extra spaces.

flex-growflex-shrink属性控制弹性项目在有多余空间的情况下应“增长”(扩展)多少,在没有多余空间的情况下应“收缩”多少。

They may take up any values ranging from 0 to any positive number. 0 || positive number

它们可以使用从0到任何正数的任何值。 0 || positive number

Let me demystify that.

让我揭开神秘面纱。

Consider the simple unordered list below. It comprises just one list item.

考虑下面的简单无序列表。 它仅包含一个列表项。

<ul>    <li>I am a simple list</li></ul>
ul {    display: flex;}

With a bit more styling, it appears like this.

有了更多的样式,它看起来像这样。

By default, the flex-grow property is set to 0. By implication, the flex-item does NOT grow to fit the entire space available.

默认情况下, flex-grow属性设置为0 。 言外之意,弹性项目不会增长以适应整个可用空间。

The value 0 is like a “turn-off” switch. The flex-grow switch is turned off.

0就像一个“关闭”开关。 flex-grow开关已关闭。

However, if you changed the flex-grow value to 1, here's what happens.

但是,如果将flex-grow值更改为1 ,则会发生这种情况。

The flex-item now “grows” to occupy all the available space. The switch is turned on!

现在,弹性项目会“ 增长”以占据所有可用空间。 开关已打开!

If you tried resizing your browser, the flex-item would also “shrink” to accommodate the new screen width.

如果您尝试调整浏览器的大小,则弹性项目也会“缩小”以适应新的屏幕宽度。

Why? By default, the shrink property is set to 1. Which means the flex-shrink switch is also turned on!

为什么? 默认情况下, shrink属性设置为1。这意味着flex-shrink开关也已打开!

I’ll take a closer look at the flex-grow and flex-shrink properties in a bit in case you still don't feel confident with your understanding of this.

我将仔细研究一下flex-growflex-shrink属性,以防您仍然对自己的理解没有信心。

3.弹性基础 (3. Flex-basis)

Remember how I said the beauty of the flex-items is being “flexible”? Well, it appears you also have a control over that.

还记得我怎么说弹性项目的美是“灵活的”吗? 好吧,看来您对此也有控制权。

The flex-basis property specifies the initial size of a flex-item. Before the flex-grow or flex-shrink properties adjust it's size to fit the container or not.

flex-basis属性指定弹性项目的初始大小。 在flex-growflex-shrink属性调整之前, flex-grow调整大小以适合容器。

The previous statement is really important- so i’m taking a moment to reinforce that.

前面的声明非常重要-因此,我花一点时间来强调这一点。

The default value is flex-basis: auto. Flex-basis can take on any values you'd use on the normal width property. That is, percentages || ems || rems || pixels etc

默认值为flex-basis: autoFlex-basis可以采用您在常规width属性中使用的任何值。 也就是说, percentages || ems || rems || pixels percentages || ems || rems || pixels percentages || ems || rems || pixels

Note that when trying to set the basis property to a zero based value, use the unit also. Use flex-basis: 0px not just flex-basis: 0

请注意,尝试将基本属性设置为从零开始的值时,请同时使用单位。 使用flex-basis: 0px不仅flex-basis: 0

I’d bring back the “one list” example here again.

我将在这里再次带回“一个列表”示例。

<ul>    <li>I am a simple list</li></ul>
ul {    display: flex}
li {    padding: 4px; /*some breathing space*/}

By default, the initial width of the flex item is influenced by the default value, flex-basis: auto.

默认情况下,弹性项目的初始宽度受默认值flex-basis: auto

The width of the flex-item is computed "automatically" based on the content size (and obviously, plus whatever padding you set too).

flex-item的宽度是根据内容大小“ 自动 ”计算的(显然,还要加上您设置的任何填充)。

This means if you increased the content in the flex-item, it automatically resizes to fit.

这意味着,如果您增加弹性项目中的内容,它将自动调整大小以适合。

<ul>    <li>I am a simple list AND I am a simple list</li></ul>

If, however, you want to set the flex-item to a fixed width, you can also do this:

但是,如果要将弹性项目设置为固定宽度,也可以执行以下操作:

li {    flex-basis: 150px;}

Now the flex-item has been constrained to a width of 150px.

现在,弹性项目已被限制为150px的宽度。

It’s getting even more interesting.

它变得越来越有趣。

4. flex的简写 (4. The flex shorthand)

The flex shorthand allows you set the flex-grow, flex-shrink and flex-basis properties all at once.

flex简写允许您一次设置flex-growflex-shrinkflex-basis属性。

When appropriate, I advice you set all three properties at once using the flex shorthand than doing so individually.

在适当的时候,我建议您使用flex速记功能一次设置所有三个属性,而不是分别设置。

li {  flex: 0 1 auto;}

The code above is equal to setting the three properties: flex-grow: 0; flex-shrink: 1; flex-basis: auto

上面的代码等于设置三个属性: flex-grow: 0; flex-shrink: 1; flex-basis: auto flex-grow: 0; flex-shrink: 1; flex-basis: auto

Please note the order.

请注意订单。

Flex-grow first, then flex-shrink, and then flex-basis. The acronym, GSB may help.

flex-shrink Flex-grow ,然后flex-shrink ,然后flex-basis 。 首字母缩写词, GSB可能会有所帮助。

What happens if you fail to set one of the values in the flex-shorthand?

如果您无法在flex-shorthand中设置其中一个值,该怎么办?

If you set only the flex-grow and flex-shrinkvalues, flex-basis would default to zero.

如果仅设置flex-growflex-shrink值,则flex-basis将默认为零。

This is called an absolute flex. And when you set only the flex-basis, you get a relative flex.

这称为绝对挠曲 。 当您仅设置flex-basis ,您将获得一个相对flex

/*this is an absolute flex item*/li {  flex: 1 1; /*flex-basis defaults to 0*/}
/*this is a relative flex item*/li {  flex-basis: 200px; /*only flex-basis is set*/}

I know what you’re thinking. What’s the purpose of the relative and absolute flex?

我知道你在想什么 相对屈曲和绝对屈曲的目的是什么?

I answer that question later in this article. Again, blind trust will suffice for now.

我将在本文稍后回答这个问题。 再次,盲目信任现在就足够了。

Let’s take a look at some very useful flex shorthand values.

让我们看一下一些非常有用的flex速记值。

1. flex: 0 1 auto (1. flex: 0 1 auto)

/*again, the "li" represents any flex-item*/li {  flex: 0 1 auto;}

This is same as writing flex: default and it's the default behavior of all flex items.

这与编写flex: default相同,它是所有flex项目的默认行为。

Let me break this down, just a bit.

让我分解一下。

It’s easier to understand this by taking a look at the flex-basis property first.

首先查看flex-basis属性会更容易理解这一点。

The flex-basis is set to auto, which means the initial width of the flex-item will be automatically determined based on the size of the contents.

flex-basis设置为auto ,这意味着flex-item的初始宽度将根据内容的大小自动确定。

Got that?

了解?

Moving on to the next property, the flex-grow value is zero. This means the flex-grow property wouldn't tamper with the initial width of the flex item.

转到下一个属性, flex-grow值为零。 这意味着flex-grow属性不会篡改flex项目的初始宽度。

The grow switch is off.

增长开关关闭。

Since flex-grow controls the “growth” of the flex-items and it’s set to zero, the flex-items will not “grow” to fit the screen.

由于flex-grow控制flex-item的“ 增长 ”并将其设置为零,因此flex-items将不会“增长”以适合屏幕。

Finally, the flex shrink value is 1. It says this — “shrink the flex-item when it is necessary”

最后,flex收缩值为1。它说- “在必要时收缩flex-item”

Here is what this looks like when applied to some flex items.

这是应用于某些弹性项目时的外观。

Notice how the flex items don’t grow. The width is computed automatically, and they shrink upon resizing the browser — if necessary.

请注意弹性项目如何不增长。 宽度是自动计算的,并且在调整浏览器大小时会缩小(如有必要)。

2. Flex: 0 0 auto (2. Flex: 0 0 auto)

/*again, the "li" represents any list-item*/
li {  flex: 0 0 auto;}

This is same as flex: none.

这与flex: none相同。

Using the same framework I established earlier, the width is computed automatically BUT the flex item does NOT grow or shrink (they are both set to zero).

使用我之前建立的相同框架,宽度会自动计算,但flex项不会增大或缩小(它们都设置为零)。

The grow and shrink switches are both off.

增长和收缩开关均关闭。

It’s essentially a fixed width element whose initial width is based off of the content size in the flex item.

它本质上是一个固定宽度的元素,其初始宽度基于flex项目中的内容大小。

See how this flex shorthand affects two flex items. One housing more content than the other.

了解此flex速记如何影响两个flex项目。 一个容纳比另一个容纳更多的内容。

The first thing you should notice is, the flex items both have different widths.

您应该注意的第一件事是,伸缩项目都具有不同的宽度。

That is expected since the widths are computed automatically, based on the content size.

这是可以预期的,因为宽度是根据内容大小自动计算的。

Try resizing your browser, and you’ll notice that the flex items don’t shrink with its width. They pop out of the parent element, and you have to scroll your browser horizontally to view all the content.

尝试调整浏览器的大小,您会注意到弹性项目不会随其宽度缩小。 它们从父元素中弹出,您必须水平滚动浏览器才能查看所有内容。

No worries, I’ll show you how to deal with this weird behavior later.

不用担心,稍后我将向您展示如何处理这种奇怪的行为。

3. Flex: 1 1 auto (3. Flex: 1 1 auto)

This is same as flex: auto.

这与flex: auto相同。

Use the framework I established earlier.

使用我之前建立的框架。

This says, "compute initial width automatically, but grow to fit the entire available space and shrink if necessary"

表示“自动计算初始宽度,但会增长以适合整个可用空间并在必要时缩小”

The grow and shrink switches are turned on, and the widths computed automatically.

增长和收缩开关打开,宽度自动计算。

This time around, the items fill up the available space and they shrink upon resizing the browser too.

这次,这些项目会填满可用空间,并且在调整浏览器大小时也会缩小。

4. Flex: "positive number" (4. Flex: "positive number")

Where “positive number” represents any positive number (without the quotes)

其中“ 正数 ”表示任何正数(不带引号)

This is the same as flex: “positive number” 1 0.

这与flex: “positive number” 1 0

flex: 2 1 0is the same as writingflex:2 2 represents any positive number.

flex: 2 1 0与写flex:2 2相同,代表任何正数。

/*again, the "li" represents any list-item*/li {  flex: 2 1 0; /*same as flex: 2*/}

Following the same framework I established earlier, this says, “set the initial width of the flex item to zero (ehm, no width?), grow the item to fill the available space, and finally shrink the item whenever possible”

按照我之前建立的相同框架,它说:“ 将flex项目的初始宽度设置为零(ehm,没有宽度?),增加项目以填充可用空间,并在可能的情况下最终收缩项目”

With the flex items having “no width”, how’s the width computed?

如果flex项目具有“ no width ”,那么如何计算宽度?

The flex-grow value takes over, and determines the extent the flex item “widens”.

flex-grow值将接管,并确定flex项目“ 拓宽 ”的程度。

That takes care of the no-width problem.

这解决了宽度问题。

It’s more practical to use this flex shorthand when you have more than one flex item whose initial widths, flex-basis are set to any zero based values e.g. 0px

当您有多个flex项目的初始宽度flex-basis设置为任何基于零的值(例如0px)时,使用此flex速记更为实用

What really happens is, the widths of the flex items are computed based on the ratios of the flex-grow value.

实际发生的是,根据flex-grow值的比率来计算弹性项目的宽度。

I’d break that down just a bit.

我将其分解一下。

Consider two list items marked up and styled below.

考虑下面标记和样式化的两个列表项。

<ul>    <li>I am One</li>    <li>I am Two</li></ul>
ul {    display: flex;}
/*first flex-item*/li:nth-child(1) {    flex: 2 1 0; /*same as just writing flex: 2*/}
/*second flex-item*/li:nth-child(2){    flex: 1 1 0;    background-color: #8cacea;}

Remember that setting flex-grow : 1 lets the flex-item fill up the available space. The grow switch is turned on.

请记住,设置flex-grow : 1可以使flex-item填充可用空间。 增长开关已打开。

Here you have two flex-items. One has aflex-grow property of 1 and the other 2, what then happens?

在这里,您有两个弹性项目。 一个具有flex-grow的特性1 ,另2 ,什么接下来会发生?

You have the grow switches turned on for both items. However, the magnitude of growth differs. 1 and 2.

您已为两个项目打开了增长开关。 但是,增长幅度有所不同。 1和2。

They both expand to fill up the available space, but in some proportion.

它们都扩展以填充可用空间,但比例有所不同。

Here’s how it works.

运作方式如下。

The latter takes up 2/3 of the available space while the former takes 1/3.

后者占可用空间的2/3,而前者占1/3。

You know how I arrived at that?

你知道我是怎么到达的吗?

Basic mathematics ratio. individual ratio / total ratio I hope you didn’t skip those math classes.

基本数学比率。 individual ratio / total ratio我希望您不要跳过那些数学课程。

You see what’s happening?

你看到发生了什么事吗?

Even though both flex-items have contents of the same size (approximately), they however take up different spaces.

即使两个弹性项目都具有相同大小的内容(大约),但是它们占用不同的空间。

The widths are not based on the content size, but the grow values.

宽度不是基于内容大小,而是基于增长值。

One is about two times the other.

一个大约是另一个的两倍。

5.自我调整 (5. Align-self)

The align-self property takes a step further in giving us so much control over flex items.

align-self属性进一步使我们对flex项有了很多控制。

You already saw how the align-items property helps in collectively aligning all flex-items within a flex-container.

您已经了解了align-items属性如何帮助将Flex容器内的所有flex-item统一对齐。

What if you wanted to change the position of a single flex-item along the cross-axis, without affecting the neighboring flex-items?

如果您想更改单个弹性项目沿横轴的位置而不影响相邻的弹性项目怎么办?

This is where the align-self property comes to the rescue.

这就是align-self属性得到拯救的地方。

It may take on any of these values: auto || flex-start || flex-end || center || baseline || stretch

它可以采用以下任何一个值: auto || flex-start || flex-end || center || baseline || stretch auto || flex-start || flex-end || center || baseline || stretch

/*target first list item*/li:first-of-type {    align-self: auto || flex-start || flex-end || center || baseline || stretch}

These are values you’re already familiar with, but as a refresher here’s how they affect a particular targeted item.

这些是您已经熟悉的值,但作为回顾,这里介绍了它们如何影响特定的目标项目。

In this case, the first item within the container.

在这种情况下,容器内的第一项。

The targeted flex-item is in red.

目标弹性项目为红色。

1.弹性端 (1. Flex-end)

flex-end aligns the targeted item to the end of the cross axis.

flex-end将目标项目与横轴flex-end对齐。

2. Center (2. Center)

center aligns the targeted item to the center of the cross axis.

center将目标项目与十字轴的center对齐。

3. Stretch (3. Stretch)

stretch “stretches” the targeted flex item to fill up the available space along the cross axis.

stretch “拉伸”目标柔性项目以沿横轴填充可用空间。

4. Baseline (4. Baseline)

baseline aligns the targeted flex item along the baseline.

baseline将目标弹性项目沿baseline对齐。

It does look like the same result as flex-start but I’m sure you understand what the baseline is.

它看起来确实与flex-start相同,但我确定您了解基线是什么。

I explained that much earlier.

我早就解释了。

5. auto (5. auto)

auto sets the value of the targeted flex item to the parent’s align-items value or stretch if the element has no parent.

auto将目标弹性项目的值设置为父align-itemsalign-items值,或者在元素没有父align-items的情况下align-items stretch

In the case below, the flex-container has an align-items value of flex-start

在以下情况下,flex容器的flex-startalign-items

This aligns all the flex-items to the start of the cross-axis.

这会将所有弹性项目与横轴的起点对齐。

The targeted flex-item now inherits the flex-start value — the parent’s align-items value.

现在,目标弹性项目会继承flex-start值-父级的align-items值。

This is the base styling on the flex-items used above. Just so you understand what’s going on even better.

这是上面使用的弹性项目的基本样式。 只是为了让您更好地了解正在发生的事情。

ul {    display: flex;    border: 1px solid red;    padding: 0;    list-style: none;    justify-content: space-between;    align-items: flex-start; /*affects all flex-items*/    min-height: 50%;    background-color: #e8e8e9;}
li {  width: 100px;  background-color: #8cacea;  margin: 8px;  font-size: 2rem;}

You’re pretty much getting ready for the fun part now :-)

您现在已经为有趣的部分做好了准备:-)

绝对和相对弹性项目。 (Absolute and Relative flex-items.)

Having covered some ground in previous sections, it’s important to clarify a few important concepts here too.

在前面的几节中介绍了一些基础知识之后,在这里还要阐明一些重要的概念也很重要。

What really is the difference between an absolute and relative flex-item?

绝对弹性项目和相对弹性项目之间的真正区别是什么?

The major difference between these two is got to do with spacing and how they are computed.

两者之间的主要区别在于间距以及它们的计算方式。

The spacing within a relative flex item is computed based on it’s content size. In an absolute flex item, it is based solely on “flex”, not content.

相对弹性项目内的间距是根据其内容大小计算的。 在绝对弹性项目中,它完全基于“弹性”,而不是内容。

Consider the markup below.

考虑下面的标记。

<ul>    <li>        This is just some random text  to buttress the point being explained.    Some more random text to buttress the point being explained.    </li>
<li>This is just a shorter random text.</li></ul>

Two list elements. One has far more texts than the other.

两个列表元素。 一个文本比另一个文本多得多。

Add a bit of styling.

添加一些样式。

ul {    display: flex; /*flexbox activated*/}
li {    flex: auto; /*remember this is same as flex: 1 1 auto;*/    border: 2px solid red;    margin: 2em;}

Here’s the result:

结果如下:

If you already forgot, flex: 1 1 auto is the same as setting: flex-grow: 1 flex-shrink: 1 and flex-basis: auto

如果您已经忘记,则flex: 1 1 auto与设置相同: flex-grow: 1 flex-shrink: 1flex-basis: auto

Using the framework I established earlier, the initial widths of the flex-items are automatically computed flex-basis: auto, and then they "grow" to fit the available space flex-grow: 1.

使用我之前建立的框架,可以自动计算flex-items的初始宽度flex-basis: auto ,然后对其进行“ 增长 ”以适应可用空间flex-grow: 1

When flex-items have their widths computed automatically, flex-basis: auto, it is based on the size of the content contained within the flex-items.

当flex-item的宽度自动计算时, flex-basis: auto ,它基于flex-items中包含的内容的大小。

The flex-items in the example above do NOT have contents of the same size. Hence, the sizes of the flex-items would be unequal.

上例中的flex-item没有相同大小的内容。 因此,弹性项目的大小将不相等。

Since the individual widths weren’t equal in the first place (it was based off content), when the items grow, the widths also stay unequal.

由于开始时各个宽度不相等(这是基于内容),所以当项目增加时,宽度也保持不相等。

The flex-items in the example above are relative flex-items.

上例中的flex-item是相对 flex-item。

Let’s make the flex-items absolute — meaning this time their widths should be based on “flex” NOT content size.

让我们将flex-items设为绝对-意味着这一次它们的宽度应基于“ flex”而非内容的大小。

A “one-liner” does the magic.

单线”就是魔术。

li {    flex: 1 ; /*same as flex: 1 1 0*/}

See the result below.

请参阅下面的结果。

Do you see both flex-items have the same widths this time?

您是否看到这两个弹性项目的宽度相同?

The initial widths of the flex-items is zero flex-basis: 0, and then they “grow” to fit the available space.

flex-items的初始宽度为零flex-basis: 0 ,然后它们“ 增长”以适应可用空间。

When there are two or more flex-items with zero based flex-basis values, they share the spacing available based on the flex-grow values.

当有两个或多个弹性项目的flex-basis值为零时,它们共享基于flex-grow值的可用间距。

I talked about this earlier.

我刚才谈到了这一点。

Now the widths aren’t computed based on content size. The widths are based on the flex value specified.

现在,不再根据内容大小来计算宽度。 宽度基于指定的柔韧性值。

So you got that. Right?

所以你明白了。 对?

Absolute flex-items have their widths based solely on flex, while relative flex items have their widths based on content size.

绝对弹性项目的宽度仅基于弹性,而相对弹性项目的宽度则基于内容大小。

自动边距对齐 (Auto-margin Alignment)

当心margin: auto在弹性项目上margin: auto对齐。 (Beware of margin: auto alignment on flex items.)

When you use margin: auto on flex-items, things can look quite weird.

当您使用margin: auto在flex-items上时,情况看起来很奇怪。

You do need to understand what's going on. It may result in unexpected results, but I'm going to explain all that.

您确实需要了解发生了什么。 这可能会导致意外的结果,但是我将解释所有这些。

When you use margin: auto on a flex-item, the direction (left, right or both) that has the value auto will take up any empty spaces available.

当您在弹性项目上使用margin: auto时,值为auto的方向(左,右或两个方向)将占用任何可用的空白空间。

That’s a difficult one to catch.

这是很难抓住的。

Here’s what I mean.

这就是我的意思。

Consider the navigation bar marked up and styled below:

考虑下面标记和样式设置的导航栏:

<ul>    <li>Branding</li>    <li>Home</li>    <li>Services</li>    <li>About</li>    <li>Contact</li></ul>
ul {    display: flex;}li {    flex: 0 0 auto;}

See the result of that below.

请参阅下面的结果。

There are a couple of things to note here:

这里有几件事要注意:

  1. The flex-grow value is set to zero. This explains why the list items don't grow

    flex-grow值设置为零。 这解释了为什么列表项没有增长

  2. The flex-items are aligned to the start of the main-axis (the default behavior)弹性项目与主轴的起点对齐(默认行为)
  3. Owing to the items being aligned to the start of the main-axis, some extra space is left on the right. You see that?由于项目与主轴的起点对齐,因此右侧留有一些额外的空间。 你看到了吗?

Now use margin: auto on the first list item (branding) and see what happens.

现在,在第一个列表项(品牌)上使用margin: auto ,看看会发生什么。

li:nth-child(1) {    margin-right: auto; /*applied only to the right*/}

What just happened?

刚才发生了什么?

The extra space that existed has now been distributed to the right of the first flex-item.

现在已经存在的多余空间已分配到第一个弹性项目的右侧。

Do you remember what I said earlier?

你还记得我刚才说的话吗?

When you use margin:auto on a flex-item, the direction (left, right or both) that has the valueauto will take up any empty spaces available.

在弹性项目上使用margin:auto时,值为auto的方向(左,右或两个方向)将占用任何可用的空白空间。

What if you wanted an auto margin alignment on both sides of a flex-item?

如果您想在弹性项目的两侧进行自动边距对齐怎么办?

/*you may use the margin shorthand to set both sides if you wish*/li:nth-child(1) {    margin-left: auto;    margin-right: auto}

Now the space is distributed across both sides of the flex-item.

现在,空间分布在弹性项目的两侧。

So, is there a trade off with the cool auto-margin alignment?

那么,是否可以通过自动调整边距进行权衡?

It appears there’s one. It can be a source of frustration if you don’t pay attention too.

似乎有一个。 如果您也没有注意的话,这可能会导致挫败感。

When you use the auto-margin alignment on a flex-item, the justify-content property no longer works.

在弹性项目上使用自动边距对齐时, justify-content属性不再起作用。

For instance, setting a different alignment option on the flex-container above via the justify-content property, has no impact on the layout.

例如,通过justify-content属性在上方的flex-container上设置其他对齐选项不会对布局产生影响。

ul {    justify-content: flex-end;}

实际用例 (Practical Use cases)

Navigation systems are a very big part of every website or application. Every website on the planet has got some sort of navigation system in place.

导航系统是每​​个网站或应用程序的重要组成部分。 地球上的每个网站都有适当的导航系统。

Take a look at these popular sites and how they approach their navigation systems.

看一看这些热门站点以及它们如何使用其导航系统。

Do you see how Flexbox can help you build these layouts more efficiently?

您是否了解Flexbox如何帮助您更有效地构建这些布局?

Take a closer look to see where the auto-margin feature may come in very handy too.

仔细研究一下自动边距功能在哪些地方也很方便。

(i)引导导航 ((i) Bootstrap Navigation)

(ii)AirBnB桌面导航 ((ii) AirBnB desktop Navigation)

(iii)Twitter桌面导航 ((iii) Twitter desktop Navigation)

I recommend you actually write code as a form of practice. I have written a practical guide here: The Most Popular Navigation Bars Created with Flexbox

我建议您实际编写代码作为一种练习。 我在这里写了一个实用指南: 用Flexbox创建的最受欢迎的导航栏

Go take a look.

快去看看

I’ll wait.

我会等。

切换弹性方向时会发生什么? (What happens when you switch flex-direction?)

Fair warning: there’s some weird stuff on the way.

合理的警告:途中有一些奇怪的东西。

When starting off with learning the Flexbox model, this part was the most confusing.

从学习Flexbox模型开始,这部分最令人困惑。

I bet a lot of newcomers to the “flex world” find it that way too.

我敢打赌,“ flex world”的许多新来者也是如此。

You remember when I talked about the default main and cross axis being in the “left to right” and “top to bottom” directions?

您还记得当我谈到默认的主轴和十字轴在“从左到右”和“从上到下”的方向时吗?

Well, you can change that too.

好吧,您也可以更改它。

This is exactly what happens when you use flex-direction: column as described in an earlier section.

如前一节所述,这正是使用flex-direction: column时发生的情况。

When you use flex-direction: column, the main and cross axis are changed as seen below.

当您使用flex-direction: column ,主轴和交叉轴将如下所示进行更改。

If you’ve ever written any text in the English language, then you already know the language is written from left to right and top to bottom.

如果您曾经用英语写过任何文本,那么您已经知道该语言是从左到右,从上到下写的。

That’s equally the direction taken for the default main and cross axis of the Flexbox, too.

同样,这也是Flexbox默认主轴和交叉轴所采用的方向。

However, on switching the flex direction to column, it no longer follows the "English Language" pattern but Japanese!

但是,将flex方向切换为column ,它不再遵循“ English Language ”模式,而是遵循日语!

Oh yes, Japanese.

哦,是的,日语。

If you’ve written any text in the Japanese language, then this will be familiar. (For the record, I’ve never written any text in Japanese.)

如果您用日语写过任何文字,就会很熟悉。 (For the record, I've never written any text in Japanese.)

Japanese text is traditionally written from top to bottom! Not so weird, huh?

Japanese text is traditionally written from top to bottom ! Not so weird, huh?

That explains why this can be a bit confusing for English writers.

That explains why this can be a bit confusing for English writers.

Take a look at this example. The standard unordered list with 3 list items, except this time I’ll change the flex-direction.

Take a look at this example. The standard unordered list with 3 list items, except this time I'll change the flex-direction.

<ul>        <li></li>        <li></li>        <li></li>    </ul>
ul {    display: flex;    flex-direction: column;}

Here’s the look before the change in direction:

Here's the look before the change in direction:

And afterward:

And afterward:

So what happened?

所以发生了什么事?

The “text” is now written in Japanese style — from top-to-down (main-axis).

The “text” is now written in Japanese style — from top-to-down (main-axis).

There’s something you may find funny, I’d love to point out.

There's something you may find funny, I'd love to point out.

You see the width of the items fill up the space, right?

You see the width of the items fill up the space, right?

If you were to change that before now, you’d just deal with the flex-basis and(or) flex-grow properties.

If you were to change that before now, you'd just deal with the flex-basis and(or) flex-grow properties.

Let's see how those affect our new layout.

Let's see how those affect our new layout.

li {    flex-basis: 100px;}

…and here’s what you’d get.

…and here's what you'd get.

Wow — what? The height is affected, but not the width?

Wow — what? The height is affected, but not the width?

As I said earlier, the flex-basis property defines the initial-width of every flex-item.

As I said earlier, the flex-basis property defines the initial-width of every flex-item.

I was wrong — or better put, I was thinking in “English”. Let’s switch to Japanese for a bit.

I was wrong — or better put, I was thinking in “ English ”. Let's switch to Japanese for a bit.

It doesn’t always have to be “width”.

It doesn't always have to be “width”.

Upon switching flex-direction, please note that every property that affected the main-axis now affects the new main-axis.

Upon switching flex-direction, please note that every property that affected the main-axis now affects the new main-axis.

A property like flex-basis that affected the width of the flex-items along the main-axis now affects the height NOT width.

A property like flex-basis that affected the width of the flex-items along the main-axis now affects the height NOT width.

The direction has been switched!

The direction has been switched!

So even if you used the flex-grow property, it'd affect the height too.

So even if you used the flex-grow property, it'd affect the height too.

Essentially, every flex property that operated on the horizontal axis (the then main-axis) now operates vertically, the new main-axis.

Essentially, every flex property that operated on the horizontal axis (the then main-axis) now operates vertically, the new main-axis.

It's just a switch in directions.

It's just a switch in directions.

Here’s one more example. I promise you’ll have a better understanding after this one.

Here's one more example. I promise you'll have a better understanding after this one.

Reduce the width of the flex-items we looked at just before now, and they no longer fill the entire space:

Reduce the width of the flex-items we looked at just before now, and they no longer fill the entire space:

li {    width: 200px;}

What if you wanted to move the list items to the center of the screen?

What if you wanted to move the list items to the center of the screen?

In English language, which is how you’ve dealt with flex-containers until now. That’d mean “move the flex-items to the center of the main-axis”.

In English language, which is how you've dealt with flex-containers until now. That'd mean “ move the flex-items to the center of the main-axis ”.

So, you’d have used justify-content: center

So, you'd have used justify-content: center

But doing that now does not work.

But doing that now does not work.

Since the direction’s changed, the center is along the cross-axis — not the main-axis.

Since the direction's changed, the center is along the cross-axis — not the main-axis.

Take a look again:

Take a look again:

So please think in terms of Japanese text.

So please think in terms of Japanese text .

The main-axis is from top-to-down, you don’t need that.

The main-axis is from top-to-down, you don't need that.

The cross-axis is from left to right. Sounds like what you need.

The cross-axis is from left to right. Sounds like what you need.

You need to “move the flex-items to the center of the cross-axis.”

You need to “move the flex-items to the center of the cross-axis.”

Any flex-container property rings a bell here?

Any flex-container property rings a bell here?

Yeah, the align-items property .

Yeah, the align-items property .

The align-items property deals with alignment on the cross-axis.

The align-items property deals with alignment on the cross-axis.

So to move those to the center, you'd do this:

So to move those to the center, you'd do this:

ul {    align-items: center;}

And voila! You’ve got the flex-items centered.

瞧! You've got the flex-items centered.

It can get a bit confusing, I know. Just go over it one more time if you need to.

It can get a bit confusing, I know. Just go over it one more time if you need to.

While studying the Flexbox model, I noticed a lot of CSS books skipped this part.

While studying the Flexbox model, I noticed a lot of CSS books skipped this part.

A bit of thinking in Japanese text would go a long way to help.

A bit of thinking in Japanese text would go a long way to help.

It’s worth understanding that all Flexbox properties work based on the flex-direction that’s in place.

It's worth understanding that all Flexbox properties work based on the flex-direction that's in place.

I’m sure you learned something new again. I’m having fun explaining this. I hope you are having fun too :-)

I'm sure you learned something new again. I'm having fun explaining this. I hope you are having fun too :-)

Oh my gosh, Flexbox solved that? (Oh my gosh, Flexbox solved that?)

Some classic problems many designers face with CSS have been trivially solved by Flexbox.

Some classic problems many designers face with CSS have been trivially solved by Flexbox.

Philip Walton, in his solved-by-flexbox project lists 6 classic problems (as of this writing).

Philip Walton , in his solved-by-flexbox project lists 6 classic problems (as of this writing).

He extensively discusses the previous limitations with CSS, and the current solution Flexbox provides.

He extensively discusses the previous limitations with CSS, and the current solution Flexbox provides.

I recommend you take a look after completing this article.

I recommend you take a look after completing this article.

In the practical section coming up, I’ll explain some of the concepts he addresses as I walk you through building a music app layout with Flexbox.

In the practical section coming up, I'll explain some of the concepts he addresses as I walk you through building a music app layout with Flexbox.

Flexbugs and gotchas for non-compliant browsers (Flexbugs and gotchas for non-compliant browsers)

If you’re the not the type of person who writes CSS in their dreams, you may want to watch this github repository.

If you're the not the type of person who writes CSS in their dreams, you may want to watch this github repository .

Some people who are smarter than I am curate a list of Flexbox bugs and their workarounds there.

Some people who are smarter than I am curate a list of Flexbox bugs and their workarounds there.

It’s the first place I look when something isn’t working as I expect.

It's the first place I look when something isn't working as I expect.

I’ll be working you through some prominent bugs in the practical section coming next too.

I'll be working you through some prominent bugs in the practical section coming next too.

So you’re covered!

So you're covered!

Building a Music App Layout with Flexbox (Building a Music App Layout with Flexbox)

After walking through the boring rigorous stuffs, you deserve some fun project.

After walking through the boring rigorous stuffs, you deserve some fun project.

It’s time to walk through a practical example and apply your newly acquired Flexbox skills.

It's time to walk through a practical example and apply your newly acquired Flexbox skills .

It took me days to come up with a good project.

It took me days to come up with a good project.

Out of the lack of a creative option, I came up with a music app layout for cats.

Out of the lack of a creative option, I came up with a music app layout for cats.

I call it catty music.

I call it catty music .

Maybe by 2036, we’d have cats singing in rock bands somewhere in Mars :-)

Maybe by 2036, we'd have cats singing in rock bands somewhere in Mars :-)

Here’s what the finished layout looks like, and it is completely laid out with Flexbox.

Here's what the finished layout looks like, and it is completely laid out with Flexbox.

You can view it online here.

You can view it online here .

If you view that on a mobile device, you’ll have a slightly different look. That’s something you’ll work on in the responsive design section of this article.

If you view that on a mobile device, you'll have a slightly different look. That's something you'll work on in the responsive design section of this article.

I’ve got a confession to make though.

I've got a confession to make though.

I’ve done something considered wrong by many.

I've done something considered wrong by many.

I’ve completely built the overall layout with Flexbox.

I've completely built the overall layout with Flexbox.

For many reasons, this may not be ideal. But it’s intentional in this scenario. I set out to show you all the things you can do with Flexbox, all wrapped up within a single project.

For many reasons, this may not be ideal. But it's intentional in this scenario. I set out to show you all the things you can do with Flexbox, all wrapped up within a single project.

If you’re curious as to when it’s considered right or wrong to use the Flexbox model, you may check out my article on that.

If you're curious as to when it's considered right or wrong to use the Flexbox model, you may check out my article on that.

Flexbox is awesome but it’s NOT welcome here!Flexbox is arguably the best thing that happened to most of us (if you write css) but does that make it perfect for all…medium.com

Flexbox is awesome but it's NOT welcome here! Flexbox is arguably the best thing that happened to most of us (if you write css) but does that make it perfect for all… medium.com

There, I got that off my chest. Now I’m sure no one’s going to yell at me after reading this.

There, I got that off my chest. Now I'm sure no one's going to yell at me after reading this.

Everything in Catty Music is laid out using the Flexbox model — this is intentional to show off what’s possible.

Everything in Catty Music is laid out using the Flexbox model — this is intentional to show off what's possible.

So let’s get this thing built!

So let's get this thing built!

As with any reasonable project, a bit of planning goes a long way sifting through inefficiencies.

As with any reasonable project, a bit of planning goes a long way sifting through inefficiencies.

Let me take you through a planned approach to building the catty music layout.

Let me take you through a planned approach to building the catty music layout.

Where do you start? (Where do you start?)

Whenever building a layout with Flexbox, you should start by looking out for what sections of your layout may stand out as flex-containers.

Whenever building a layout with Flexbox, you should start by looking out for what sections of your layout may stand out as flex-containers.

You then leverage the powerful alignment properties Flexbox makes available.

You then leverage the powerful alignment properties Flexbox makes available.

细目分类 (The Breakdown)

You may have the overall containing body as a flex container (contained within the red border in the image below) and have the other sections of the layout split into flex-items (items 1 and 2).

You may have the overall containing body as a flex container (contained within the red border in the image below) and have the other sections of the layout split into flex-items (items 1 and 2).

This makes total sense, as item 1 contains every part of the layout other than the “footer” — the section that contains the music control buttons.

This makes total sense, as item 1 contains every part of the layout other than the “ footer” — the section that contains the music control buttons.

Did you know that a flex-item could also be made a flex-container?

Did you know that a flex-item could also be made a flex-container?

Yep, it’s possible!

Yep, it's possible!

You can nest as deep as you want (though the sane thing to do is to keep this to a reasonable level).

You can nest as deep as you want (though the sane thing to do is to keep this to a reasonable level).

So, with that new revelation comes this…

So, with that new revelation comes this…

Item 1 (the first flex-item) may also be made a flex container.

Item 1 (the first flex-item) may also be made a flex container.

The sidebar(item 1b) and main section(item 1a) would then be flex-items.

The sidebar(item 1b) and main section(item 1a) would then be flex-items.

You’re still with me, right?

You're still with me, right?

Decomposing your layout like this gives you a really good mental model to work with.

Decomposing your layout like this gives you a really good mental model to work with.

When you begin building even more complex layouts with the Flexbox model, you’d see how vital this is.

When you begin building even more complex layouts with the Flexbox model, you'd see how vital this is.

You do not need a fancy image like the ones above. A simple rough paper sketch should be just fine to get you going.

You do not need a fancy image like the ones above. A simple rough paper sketch should be just fine to get you going.

You remember I said you could nest as deep as you wanted? It appears you may do one more nesting here.

You remember I said you could nest as deep as you wanted? It appears you may do one more nesting here.

Take a look at the main section above (Item 1a).

Take a look at the main section above (Item 1a).

It could also be made a flex container to house the sections highlighted below. “Item 1a — A” and “Item 1a — B

It could also be made a flex container to house the sections highlighted below. “ Item 1a — A ” and “ Item 1a — B

You may decide not to make the main section (item 1a) a flex container and just put within it two “divs” to house the highlighted sections.

You may decide not to make the main section (item 1a) a flex container and just put within it two “divs” to house the highlighted sections.

Yes that’s possible, since “Item 1a — A” and “Item 1a — B” are stacked vertically.

Yes that's possible, since “ Item 1a — A ” and “ Item 1a — B ” are stacked vertically.

By default, “divs” stack vertically. It’s how the box model works.

By default, “ divs ” stack vertically. It's how the box model works.

If you choose to make the main section a flex-container, you get the powerful alignment properties at your disposal. Just in case you need them at any time.

If you choose to make the main section a flex-container, you get the powerful alignment properties at your disposal. Just in case you need them at any time.

The “flex” in Flexbox means flexible.

The “ flex ” in Flexbox means flexible.

Flex-containers are by default flexible, kind off responsive.

Flex-containers are by default flexible, kind off responsive.

This may be another reason to use a flex-container over regular “divs”. This depends on the case scenario though.

This may be another reason to use a flex-container over regular “ divs ”. This depends on the case scenario though.

I’ll touch up on some other things as you build catty music. You should get to writing some code now.

I'll touch up on some other things as you build catty music. You should get to writing some code now.

Basic HTML Setup (Basic HTML Setup)

Start off with the basic HTML set up below.

Start off with the basic HTML set up below.

<!DOCTYPE html>  <html>  <head>  <title>Catty Music</title>  </head>  <body>
<main></main> <!--to contain the main section of the app-->
<footer></footer> <!--to contain the music control buttons and song details-->
</body></html>

So style this …

So style this …

html,  body {    height: 100%; /*setting this explicitly is important*/  }
body {    display: flex; /*flex superpowers activated! */    flex-direction: column; /*Stack the flex-items (main and footer elements) vertically NOT horizontally*/  }

The first step to using the Flexbox model is establishing a flex container.

The first step to using the Flexbox model is establishing a flex container.

This is exactly what the code above does. It sets the body element’s display property to flex

This is exactly what the code above does. It sets the body element's display property to flex

Now you have a flex container, the body element.

Now you have a flex container, the body element.

The flex items are defined too (item 1 and item 2) — as in the breakdown earlier done.

The flex items are defined too (item 1 and item 2) — as in the breakdown earlier done.

Note that you should take another look at the images I showed in my initial breakdown earlier if this concept still seems fuzzy for you.

Note that you should take another look at the images I showed in my initial breakdown earlier if this concept still seems fuzzy for you.

Keeping the image of the end in view, you should get the flex-items working.

Keeping the image of the end in view, you should get the flex-items working.

Make the footer stick to the bottom. (Make the footer stick to the bottom.)

The footer which houses the music controls sticks to the bottom of the page while the main section fills up the remaining space.

The footer which houses the music controls sticks to the bottom of the page while the main section fills up the remaining space.

How do you do that?

你是怎样做的?

main {    flex: 1 0 auto; /*fill the available space*/  }
footer {    flex: 0 0 90px; /*don't grow or shrink - just stay at a height of 90px.*/  }

Please see the comments in the code listing above.

Please see the comments in the code listing above.

Thanks to the flex-grow property. It's relatively easy to have the main section fill the entire space.

Thanks to the flex-grow property. It's relatively easy to have the main section fill the entire space.

Just set the flex-grow value to 1. You should also set the flex-shrink property to zero. Why?

Just set the flex-grow value to 1. You should also set the flex-shrink property to zero. 为什么?

The reason may not be evident here because the flex-direction is changed.

The reason may not be evident here because the flex-direction is changed.

In some browsers, there’s a bug that allows flex-items to shrink below their content size. It’s quite a weird behavior.

In some browsers, there's a bug that allows flex-items to shrink below their content size. It's quite a weird behavior.

The workaround to this bug is to keep the flex-shrink value at 0 , not the default value of 1, and also set the flex-basis property to auto.

The workaround to this bug is to keep the flex-shrink value at 0 , not the default value of 1 , and also set the flex-basis property to auto .

It’s like saying: “Please compute the size of the flex item automatically, but never shrink.”

It's like saying: “Please compute the size of the flex item automatically, but never shrink.”

With this shorthand value, you still get the default behavior of flex items.

With this shorthand value, you still get the default behavior of flex items.

The flex item would shrink upon resizing the browser. The resizing isn’t based on the shrink property. It is based on the recomputing the width of the flex item automatically. flex-basis: auto

The flex item would shrink upon resizing the browser. The resizing isn't based on the shrink property. It is based on the recomputing the width of the flex item automatically. flex-basis: auto

This will cause the flex-item to be at least as big as its width or height (if declared) or its default content size.

This will cause the flex-item to be at least as big as its width or height (if declared) or its default content size.

Please don’t forget the framework for which I broke down the flex-shorthand properties. There's going to be a lot of shorthand stuff coming up.

Please don't forget the framework for which I broke down the flex-shorthand properties. There's going to be a lot of shorthand stuff coming up.

Now that things are coming together, let’s put in a bit of styling to define spacing and colors:

Now that things are coming together, let's put in a bit of styling to define spacing and colors:

body {    display: flex;    flex-direction: column;    background-color: #fff;    margin: 0;    font-family: Lato, sans-serif;    color: #222;    font-size: 0.9em;  }  footer {    flex: 0 0 90px;    padding: 10px;    color: #fff;    background-color: rgba(61, 100, 158, .9);  }

Nothing magical yet.

还没有什么神奇的。

Here’s what you should have now:

Here's what you should have now:

Seeing how things are beginning to take shape, you’ll make it even better.

Seeing how things are beginning to take shape, you'll make it even better.

Fix the sidebar. (Fix the sidebar.)

If you’re coding along, update your HTML document.

If you're coding along, update your HTML document.

<main>  <aside> <!--This represents the sidebar and contained in it are icon sets from font-awesome-->    <i class="fa fa-bars"></i>    <i class="fa fa-home"></i>    <i class="fa fa-search"></i>    <i class="fa fa-volume-up"></i>    <i class="fa fa-user"></i>    <i class="fa fa-spotify"></i>    <i class="fa fa-cog"></i>    <i class="fa fa-soundcloud"></i>  </aside>
<section class="content"> <!--This section will house everything other than the sidebar-->  </section>
</main>

The listing above is quite explanatory.

The listing above is quite explanatory.

For the icon sets, I am using the popular Font Awesome library.

For the icon sets, I am using the popular Font Awesome library.

Having your desired icon is as simple as just adding a CSS class. This is what I’ve done within the aside tag.

Having your desired icon is as simple as just adding a CSS class. This is what I've done within the aside tag.

As explained earlier, the “main” section above will also be made a flex container. The sidebar (represented by the aside tag), and the section will be flex-items.

As explained earlier, the “ main ” section above will also be made a flex container. The sidebar (represented by the aside tag), and the section will be flex-items.

main {  flex: 1 0 auto; /*Is a flex item*/  display: flex; /*I just included this! - now a flex container with flex items: sidebar & main content section*/  }

Alright, this is getting interesting, huh?

Alright, this is getting interesting, huh?

Now you have the main section as a flex container. Deal with one of its flex items, the sidebar.

Now you have the main section as a flex container. Deal with one of its flex items, the sidebar.

Just as you made the footer stick to the bottom of the page, you also want the sidebar to stick — this time to the left of the page.

Just as you made the footer stick to the bottom of the page, you also want the sidebar to stick — this time to the left of the page.

aside {       flex: 0 0 40px; /*do not grow or shrink. Stay fixed at 40px*/ }

The sidebar should have icons stacked vertically.

The sidebar should have icons stacked vertically.

You can make the sidebar a flex-container and give it a flex-direction that lets all icons stack vertically.

You can make the sidebar a flex-container and give it a flex-direction that lets all icons stack vertically.

Then apply an alignment property to have the icons in position.

Then apply an alignment property to have the icons in position.

See how you may do this in the listing below.

See how you may do this in the listing below.

aside {       /* ...  */
display: flex; /*Now a flex-container too*/          flex-direction: column; /*stack icons vertically*/          /*since direction is changed, this works on the vertical direction*/
justify-content: space-around;
align-items: center; /*direction is changed! This affects the horizontal direction. Places Icons in the center*/          background-color: #f2f2f2; /*make me pretty*/  }
aside i.fa {        font-size: 0.9em;  /*font size for the icons*/  }

I’ve obsessively commented through the code above and now see how pretty everything is laid out.

I've obsessively commented through the code above and now see how pretty everything is laid out.

Super neat with few lines of codes.

Super neat with few lines of codes.

Reasonable codes, no messy hacks.

Reasonable codes, no messy hacks.

The main content section is currently empty. Don’t forget it’s the second list-item. The sidebar is first.

The main content section is currently empty. Don't forget it's the second list-item. The sidebar is first.

Put in some stuff there.

Put in some stuff there.

Adding content to the main section. (Adding content to the main section.)

You may take a look at the finished project again, so you don’t lose sight of where this is headed.

You may take a look at the finished project again, so you don't lose sight of where this is headed.

More importantly, it’d help you understand the next code listing.

More importantly, it'd help you understand the next code listing.

Update your HTML document and have these within the .content section.

Update your HTML document and have these within the .content section.

<section class="content"> <!--This section was empty. Populating it with content-->
<div class="music-head"> <!--First list item: contains music details-->
<img src="data:images/cattyboard.jpg" /> <!--Album art-->
<section class="catty-music"> <!--other details of the album-->          <div>            <p>CattyBoard Top 100 Single Charts (11.06.36)</p>            <p>Unknown Artist</p>            <p>2016 . Charts . 100 songs</p>          </div>
<div> <!--Music controls-->            <i class="fa fa-play">  Play all</i>            <i class="fa fa-plus">  Add to</i>            <i class="fa fa-ellipsis-h">  More</i>          </div>     </section>
</div> <!--end .music-head-->
<!--Second list item: Contains a list of all songs displayed-->
<ul class="music-list">        <li>          <p>1. One Dance</p>          <p>Crake feat CatKid & Cyla</p>          <p>2:54</p>          <p><span class="catty-cloud">CATTY CLOUD SYNC</span></p>      </li>
<li>          <p>2. Panda</p>          <p>Cattee</p>          <p>4:06</p>          <p><span class="catty-cloud">CATTY CLOUD SYNC</span></p>      </li>
<li>          <p>3. Can't Stop the Feeling!</p>          <p>Catin Cimberlake</p>          <p>3:56</p>          <p><span class="catty-cloud">CATTY CLOUD SYNC</span></p>      </li>
<li>          <p>4. Work From Home</p>          <p>Cat Harmony feat Colla</p>          <p>3:34</p>          <p><span class="catty-cloud">CATTY CLOUD SYNC</span></p>      </li>    </ul></section>

Um, I added a bit more than the last time but its pretty simple.

Um, I added a bit more than the last time but its pretty simple.

I populated the empty content section with a div that holds the album art and some details of the catty album.

I populated the empty content section with a div that holds the album art and some details of the catty album.

The ul holds a list of songs from the album.

The ul holds a list of songs from the album.

The song title, artiste, duration and "catty cloud sync" are contained in individual paragraphs within the list.

The song title , artiste , duration and " catty cloud sync " are contained in individual paragraphs within the list.

So what are you going to do with styling?

So what are you going to do with styling?

See what I did?

See what I did?

First off, you should make the .content section a flex container.

First off, you should make the .content section a flex container.

.content {    display: flex;
flex: 1 1 auto; /*this makes sure the section grows to fill the entire available space and shrinks too*/
flex-direction: column;}

You should also deal with it’s flex-items:

You should also deal with it's flex-items:

.music-head {   flex: 0 0 280px; /*Same memo, don't grow or shrink - stay at 280px*/
display: flex;    padding: 40px;  background-color: #4e4e4e;}
.music-list {    flex: 1 0 auto;    list-style-type: none;    padding: 5px 10px 0px;}

.music-head holds the album art and other related album details.

.music-head holds the album art and other related album details.

Same memo, do not grow or shrink but keep a height of 280px.

Same memo, do not grow or shrink but keep a height of 280px.

Height? Not width? Yes!

Height? Not width? 是!

The parent element already had the flex-direction switched.

The parent element already had the flex-direction switched.

Oh, you're going to need this to be a flex-container later on too. So put in display: flex

Oh, you're going to need this to be a flex-container later on too. So put in display: flex

.music-list holds the list of songs and it fills up the remaining available space shared with .music-head above.

.music-list holds the list of songs and it fills up the remaining available space shared with .music-head above.

This doesn’t feel very pretty yet but c’mon you’re doing great if still following.

This doesn't feel very pretty yet but c'mon you're doing great if still following.

Thumbs up.

Thumbs up.

There are a few problems here.

There are a few problems here.

  1. The list of songs look terrible.

    The list of songs look terrible.

2. The section containing the music art has really ugly looking text.

2. The section containing the music art has really ugly looking text .

Again, I’ll walk you through solving these problems.

Again, I'll walk you through solving these problems.

Below are the solutions I propose.

Below are the solutions I propose.

Dealing with the list of songs (Dealing with the list of songs)

Each list of songs contain 4 paragraphs. Song title, artiste, duration, and “catty cloud sync”.

Each list of songs contain 4 paragraphs. Song title, artiste, duration, and “catty cloud sync”.

There’s got to be a way to put all of this in one line with each paragraph taking up equal space along this line.

There's got to be a way to put all of this in one line with each paragraph taking up equal space along this line.

Flexbox to the rescue!

Flexbox to the rescue!

The concept here is the same employed in many grid systems.

The concept here is the same employed in many grid systems.

Translate that to code.

Translate that to code.

li {  display: flex; /*Paragraphs are now displayed on one line*/  padding: 0 20px; /*Some breahing space*/  min-height: 50px;}
li p {  flex: 0 0 25%; /*This is the sweet sauce*/}

You see what’s happening there with the paragraphs?

You see what's happening there with the paragraphs?

flex: 0 0 25%;

“Don’t grow or shrink but each paragraph should take up 25% of the available space”.

“Don't grow or shrink but each paragraph should take up 25% of the available space” .

The space is shared equally among the paragraphs.

The space is shared equally among the paragraphs.

Using this Technique (Using this Technique)

This technique is invaluable. You can use it to create unequal content areas. Say, a 2 column view.

This technique is invaluable. You can use it to create unequal content areas. Say, a 2 column view.

One section can take up 60% of the available space, and the other 40%

One section can take up 60% of the available space, and the other 40%

.first-section: 0 0 60%;
.second-section: 0 0 40%;

You can use this technique for making grid systems.

You can use this technique for making grid systems.

Here is how the lists should look now.

Here is how the lists should look now.

Give the lists alternating colors, deal with the “catty cloud sync” label too.

Give the lists alternating colors, deal with the “catty cloud sync” label too.

li span.catty-cloud {  border: 1px solid black;  font-size: 0.6em;  padding: 3px;}
li:nth-child(2n) {  background-color: #f2f2f2;}

So, you’re killing it, and really getting to understand the flexbox lingo better.

So, you're killing it, and really getting to understand the flexbox lingo better.

This is what you should have now.

This is what you should have now.

The second problem will be dealt with now.

The second problem will be dealt with now.

Making the album details text look prettier. (Making the album details text look prettier.)

Really simple stuff going on below.

Really simple stuff going on below.

.catty-music{  flex: 1 1 auto;  display: flex;  flex-direction: column;  font-weight: 300;  color: #fff;  padding-left: 50px;}
.catty-music div:nth-child(1){  margin-bottom: auto;}
.catty-music div:nth-child(2){  margin-top: 0;}
.catty-music div:nth-child(2) i.fa{  font-size: 0.9em;  padding: 0 0.7em;  font-weight: 300;}.catty-music div:nth-child(1) p:first-child{  font-size: 1.8em;  margin: 0 0 10px;}
.catty-music div:nth-child(1) p:not(:first-child){  font-size: 0.9em;  margin: 2px 0;}

and you did it.

and you did it.

You’re pretty much done.

You're pretty much done.

A quick exercise (A quick exercise)

I’ve saved the footer for you to work on as an exercise.

I've saved the footer for you to work on as an exercise.

Try fixing the footer yourself. Just employ the same techniques. You can do this you know?

Try fixing the footer yourself. Just employ the same techniques. You can do this you know?

If you get stuck, you can always check out the full source code for catty music.

If you get stuck, you can always check out the full source code for catty music.

You may break the entire footer into flex-items too, and get going from there.

You may break the entire footer into flex-items too, and get going from there.

Wow. I can’t believe you got to this point. That’s great! You’re becoming a Flexbox ninja now.

哇。 I can't believe you got to this point. 那很棒! You're becoming a Flexbox ninja now.

Next, you will see how Flexbox helps with responsive designs.

Next, you will see how Flexbox helps with responsive designs.

Responsive design with Flexbox (Responsive design with Flexbox)

Books have been written on responsive design, good books at that.

Books have been written on responsive design, good books at that.

Since this article focuses on the Flexbox model, I wouldn’t be taking a deep plunge into the general state of responsive designs.

Since this article focuses on the Flexbox model, I wouldn't be taking a deep plunge into the general state of responsive designs.

Like I stated somewhere earlier, we do get some responsiveness out of the box with the Flexbox model.

Like I stated somewhere earlier, we do get some responsiveness out of the box with the Flexbox model.

Flexbox as in “flexible box”.

Flexbox as in “ flexible box ”.

However, it is possible to target various screen sizes via media queries and then change the flex behavior.

However, it is possible to target various screen sizes via media queries and then change the flex behavior.

Here’s an example.

这是一个例子。

The handy unordered list comes to the rescue again.

The handy unordered list comes to the rescue again.

<ul>    <li>Home</li>    <li>About</li>    <li>Contact</li>    <li>Register</li>    <li>Login</li>  </ul>

and with a bit of styling…

and with a bit of styling…

ul {        list-style-type: none;        display: flex;        border: 1px solid #4e4e4e;    }
li {        flex: 0 0 auto;        padding: 10px;        margin: 10px;        background-color: #8cacea;        color: #fff;        font-size: 1em;    }

You’re a pro at this flex stuff now, so you understand what’s going on up there.

You're a pro at this flex stuff now, so you understand what's going on up there.

Here’s how the navigation bar looks.

Here's how the navigation bar looks.

While this may be cool for desktops and tablets, at certain screen sizes it particularly doesn’t look good.

While this may be cool for desktops and tablets, at certain screen sizes it particularly doesn't look good.

On mobile, you’d want to stack the nav items vertically.

On mobile, you'd want to stack the nav items vertically.

Then comes in media queries.

Then comes in media queries.

@media screen and (max-width: 769px) {
/* code here only applies to screen devices that have a width lesser than 769px*/         ul {        flex-direction: column; /* On smaller devices, switch the direction*/    }
}

If you knew a few things about responsive designs before now, that’s great.

If you knew a few things about responsive designs before now, that's great.

Just transpose the Flexbox model unto your existing knowledge and you’re good to go.

Just transpose the Flexbox model unto your existing knowledge and you're good to go.

By the way, I made the assumption that you understand what media queries are.

By the way, I made the assumption that you understand what media queries are.

If you don’t, see the quick brief below.

If you don't, see the quick brief below.

媒体查询 (Media Queries)

Media queries are at the heart of responsive design. They let you target specific screen sizes and specify codes to be run on the devices alone.

Media queries are at the heart of responsive design. They let you target specific screen sizes and specify codes to be run on the devices alone.

The most popular form in which media queries are used is something called the @media rule.

The most popular form in which media queries are used is something called the @media rule .

It looks like this:

看起来像这样:

@media screen and (max-width: 300px) {  /*write your css in this code block*/}

Looking at it, you can almost guess what that does.

Looking at it, you can almost guess what that does.

“For a screen device with a maximum width of 300px … do this and that

“For a screen device with a maximum width of 300px … do this and that

Any styles within the code block will only apply to devices that match the expression, “ screen and (max-width: 300px)”

Any styles within the code block will only apply to devices that match the expression, “ screen and (max-width: 300px)”

I guess that helped clear up some confusion.

I guess that helped clear up some confusion.

Quick Exercise (Quick Exercise)

Catty music is displayed differently on mobile devices. That’s great news. What’s even better is you should try to recreate this.

Catty music is displayed differently on mobile devices. 这真是个好消息。 What's even better is you should try to recreate this.

In the event that you get stuck, the link to the repository for this tutorial is in the next section. The solution to this is also in the repo.

In the event that you get stuck, the link to the repository for this tutorial is in the next section. The solution to this is also in the repo.

You’re almost at the end!

You're almost at the end!

In the concluding section, I’ll discuss browser support, helpful links and resources to get you moving.

In the concluding section, I'll discuss browser support, helpful links and resources to get you moving.

结论 (Conclusion)

You’ve learned how to use the flex-container and flex-item alignment properties.

You've learned how to use the flex-container and flex-item alignment properties.

I walked you through an understanding of absolute and relative flex, auto-margin alignments and switching flex direction.

I walked you through an understanding of absolute and relative flex, auto-margin alignments and switching flex direction.

You also had a chance to apply your “flex skills” to building Catty Music and then I touched up on responsive design too.

You also had a chance to apply your “ flex skills” to building Catty Music and then I touched up on responsive design too.

It’s been a long ride indeed.

It's been a long ride indeed.

Now, I’d explain some final concepts to you. Help you with resources and links I think you’ll find very helpful.

Now, I'd explain some final concepts to you. Help you with resources and links I think you'll find very helpful.

How's the browser support for Flexbox? (How’s the browser support for Flexbox?)

This is a common question asked when looking to use the Flexbox model in production.

This is a common question asked when looking to use the Flexbox model in production.

I can’t answer the question perfectly, but the caniuse website does justice to this.

I can't answer the question perfectly, but the caniuse website does justice to this.

Here’s a screenshot from caniuse, and browser support is quite impressive. You may see for yourself here.

Here's a screenshot from caniuse , and browser support is quite impressive. You may see for yourself here .

Early in my career, I glanced over caniuse many times and still could not grasp what the data represented meant. So here’s a brief explanation.

Early in my career, I glanced over caniuse many times and still could not grasp what the data represented meant. So here's a brief explanation.

At the right bottom of the caniuse website is a legend.

At the right bottom of the caniuse website is a legend.

Take a look at the image above, or just visit the site, find the legend and you’d be good to go.

Take a look at the image above, or just visit the site, find the legend and you'd be good to go.

That’s actually all there is to it.

That's actually all there is to it.

额外资源 (Additional resources)

I hope you find these helpful:

I hope you find these helpful:

  1. Get the entire Understanding Flexbox article as a PDF document — direct link

    Get the entire Understanding Flexbox article as a PDF document — direct link

  2. The Flexbox Interactive Course

    The Flexbox Interactive Course

  3. Play with the Catty Music code online

    Play with the Catty Music code online

  4. The Repo for the entire “Understanding Flexbox” tutorial

    The Repo for the entire “Understanding Flexbox” tutorial

  5. Flexbox Froggy: A Cool Flexbox Game

    Flexbox Froggy: A Cool Flexbox Game

Finally, I must say thanks for following along.

Finally, I must say thanks for following along.

想成为专业人士吗? (Want to become Pro?)

Download my free CSS Grid cheat sheet, and also get two quality interactive Flexbox courses for free!

下载我的免费CSS Grid备忘单,并免费获得两本优质的交互式Flexbox课程!

Get them now

立即获取

翻译自: https://www.freecodecamp.org/news/understanding-flexbox-everything-you-need-to-know-b4013d4dc9af/

flexbox:1.0.0

flexbox:1.0.0_了解Flexbox:您需要了解的一切相关推荐

  1. html中的box布局,CSS3 Flexbox 布局完全指南(图解 Flexbox 布局详细教程)

    背景 Flexbox 布局(也叫Flex布局,弹性盒子布局)模块( W3C 候选推荐,截止到2017年10月)旨在提供一个更有效地布局.对齐方式,并且能够使容器中的子元素大小未知或动态变化情况下仍然能 ...

  2. 问道区块链_区块链学习_v1.0.0_持续更新。。。

    本系列内容参考图 创建 共识网络 调用 部署 挖矿 消耗 编写 超级链组件 节点 多节点 账号 智能合约 合约账号 燃料耗品代币 开发者 区块 尊重原创,转载请注明出处https://blog.csd ...

  3. DotNetBar for Windows Forms 12.9.0.0_冰河之刃重打包版及制作Visual Studio C#项目模板文件详解...

    关于 DotNetBar for Windows Forms 12.9.0.0_冰河之刃重打包版 --------------------11.8.0.8_冰河之刃重打包版-------------- ...

  4. css flexbox模型_如何将Flexbox后备添加到CSS网格

    css flexbox模型 I shared how to build a calendar with CSS Grid in the previous article. Today, I want ...

  5. [Flexbox] Using order to rearrange flexbox children

    Using the order property we alter the order in which flexbox children appear on the page, without ma ...

  6. vux flexbox使用_指南针与Flexbox结合使用入门

    vux flexbox使用 There is no doubt that flexbox is an effective solution for laying out web pages. Howe ...

  7. css flexbox模型_通过Flexbox Froggy游戏自学CSS Flexbox

    过去,我们只介绍了flexbox及其工作原理. 但是实际上将flexbox应用于您的工作流程可能会遇到挑战,因为它是CSS规范中如此复杂的补充. 使用Flexbox Froggy,您可以通过有趣的涉及 ...

  8. 网关 0.0.0.0_久违的升级——全新米家智能多模网关

    纵横沙场若干年的米家多功能网关终于迎来了升级--米家智能多模网关. 新的米家智能多模网关以及光照传感器依然来自小米生态链的绿米联创. 外观方面,小米米家智能多模网关更简洁了,上表面仅有指示灯和米家标志 ...

  9. mingw w64 v8.0.0_使用Visual Studio Code和MinGW编译运行C++代码

    官网:<Using Mingw in Visual Studio Code>,本文稍做了简化,喜英文版可直接移步. 工具准备 首先应该准备如下工具: 安装对应版本的Visual Studi ...

  10. 网关为0.0.0.0_距离ETH 2.0仅7天,目标价为?美元

    作者:Kylin 编辑:小回 ETH已经轻松突破500美元大关,然后几乎没有阻力地突破600美元大关,随着ETH2.0的到来,ETH将会突破多少美元? 2020年,比特币.以太坊等主流币在一众传统主流 ...

最新文章

  1. 推荐几首好听的Coldplay的歌
  2. Android 开发中常用小技巧
  3. word2vec原理_word2vec论文阅读笔记
  4. Ajax跨域请求以及乱码解决
  5. numpy的增删改查操作
  6. 使用jsoncpp解析生成json
  7. SQL Server – QP的另一个X射线
  8. Xcode 6 免证书真机调试
  9. HTTP响应码及其含义
  10. Day01_FAT12 文件系统
  11. VideoPlayer取某一帧图片
  12. 随机过程在计算机领域的应用,随机过程与排队论——及其在计算机领域中的应用.doc...
  13. win7 虚拟wifi服务器,在win7下建立虚拟wifi
  14. Vue 使用 Apache Echarts 绘制地图(省市、地区)
  15. Python 实现PPPOE自动拨号
  16. Python3 - 补充知识点之HTML 、JavaScript、CSS (第五天)
  17. css焦点图片裁切技术
  18. AV终结者新变种(随机7位字母病毒)的分析
  19. 经济学积累(二)一些经济学词汇及概念
  20. 安迪·鲁宾支持的猫头鹰实验室刚推出了一款机器人视频会议摄像机

热门文章

  1. win10中常用快捷键 (包括切换窗口、打开我的电脑等快捷键)
  2. java程序设计基础陈国君_Java程序设计基础(第6版)
  3. 最可怕联想win7 64位旗舰版下载
  4. QT windows ICO图标制作方法
  5. 设置计算机开机密码的步骤,电脑设置开机密码的方法
  6. 关于csv文件最大行数和最大列数
  7. OKR测试试卷模板(进阶)
  8. 计算机cpu后面字母代表什么意思,英特尔CPU型号中最后的字母什么意思?如有不懂欢迎驻足停留...
  9. 密西根州立大学计算机qs分数,2020年密歇根州立大学QS世界排名
  10. Python的IDLE无法打开