Skip to content

Flexbox

Web Basics — HTML & CSS Lesson 20 1:58 English narration · English + 中文 subtitles burned in

space play · ←/→ 5s · j/l 10s · f fullscreen · ,/. speed

Chapters

Transcript
Everything you have built so far stacks downward, because that is what block boxes do. 你到目前为止做的一切都是往下堆的,因为块级盒子就是这样。
But a navigation bar, a row of cards, a toolbar — those need to sit across the page. 但导航栏、一排卡片、一条工具栏——这些需要横着排在页面上。
Add display flex to the box that holds them and its children line up side by side, immediately. 给装着它们的那个盒子加上 display: flex, 它的子元素立刻就并排排开了。
Nothing about the three boxes changed. 那三个盒子本身什么都没变。
Only their parent did. 变的只是它们的父元素。
That is the point people miss, so it is worth saying plainly. 这正是人们最容易忽略的地方,所以要说清楚。
Display flex goes on the container — the box that holds the others — not on the boxes you want moved. display: flex 写在容器上——也就是装着其它盒子的那个—— 而不是写在你想让它移动的那些盒子上。
Put it on one of the spans instead and nothing happens, because flex does not change how a box behaves. 写在其中一个 span 上,什么也不会发生, 因为 flex 改变的不是一个盒子自己的表现。
It changes how a box arranges its children. 它改变的是这个盒子如何安排它的子元素。
Once a box is flex, you decide what happens to the room left over along the row. 一旦盒子变成 flex,你就来决定这一行上多出来的空间该怎么办。
By default the children bunch at the start. 默认情况下,子元素都挤在开头。
Space-between sends the first to the far left, the last to the far right, and shares the rest of the gap between them, so they end up pushed apart. space-between 把第一个推到最左,最后一个推到最右, 再把剩下的间隙平分给它们中间,于是它们被撑开。
Look carefully: the boxes did not change size at all. 仔细看:这些盒子的大小完全没变。
Only the leftover room moved. 移动的只是那些多余的空间。
Put the two together with the background colour and padding you learned earlier, and you have a real navigation bar — the kind on the top of most websites — in four lines of CSS. 把这两条和你前面学过的背景色、内边距放在一起, 你就得到了一条真正的导航栏——大多数网站顶部的那种—— 只用了四行 CSS。
Now the tasks: turn the box into a row with display flex, then spread its children with space-between. 现在做那两道题: 用 display: flex 把盒子变成一行, 再用 space-between 把它的子元素撑开。
Four things to take with you. 带走四点。
One: display flex puts a box's children in a row. 第一:display: flex 让一个盒子的子元素排成一行。
Two: it goes on the container, never on the children. 第二:它写在容器上,绝不写在子元素上。
Three: justify-content decides where the spare room goes. 第三:justify-content 决定多余的空间去哪里。
Four: gap adds an even space between every child. 第四:gap 在每个子元素之间加上均匀的间距。
Now build the row. 现在把那一行做出来。

Log in or create account

IGCSE, A-Level & AP