Skip to content

Width and centering

Web Basics — HTML & CSS Lesson 19 2:09 English narration · English + 中文 subtitles burned in

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

Chapters

Transcript
Here is something you may not have noticed: a block box is already as wide as the page. 有件事你也许没注意到:块级盒子本来就和页面一样宽。
It has been all along — you just could not see the edges without a background colour. 它一直都是——只是没有背景色,你看不见它的边缘。
Set width to three hundred pixels wide and it becomes a narrow box instead. 把 width 设成 300 像素,它就变成了一个窄盒子。
And look where it is: it stays on the left, because narrowing a box does not move it. 再看它在哪儿:它还待在左边, 因为把盒子变窄,并不会把它挪走。
There is a gentler version worth knowing on day one. 还有一个更温和的写法,值得第一天就知道。
Width says exactly this wide, always. width 说的是"永远正好这么宽"。
Max-width says at most this wide — and narrower if the screen is. max-width 说的是"最多这么宽"——屏幕更窄时它就更窄。
Why that matters: a fixed six hundred pixels on a four hundred pixel phone means your visitor scrolls sideways to read every line. 为什么这重要: 在一部 400 像素宽的手机上写死 600 像素, 意味着你的访客读每一行都要左右滑动。
Max-width avoids that for free, on every screen, without you writing anything extra. max-width 在任何屏幕上都免费避免了这个问题,你不用多写一行代码。
Now, how do you move that narrow box into the middle? 那么,怎么把这个窄盒子挪到中间去?
Not with text-align — that moves the words, not the box. 不是用 text-align——那移动的是文字,不是盒子。
You use margin, with the value zero auto. 要用 margin,值写成 0 auto。
Zero means no top or bottom margin. 0 表示上下不要外边距。
Auto means: work out what is left over on each side and make the two equal. auto 的意思是:算出两边各剩下多少,然后让它们相等。
Equal side margins put the box in the centre. 两边外边距相等,盒子就在正中间。
That is the whole mechanism. 整个机制就是这样。
Which explains the order the tasks are in. 这也解释了这两道题为什么是这个顺序。
Write margin zero auto on a box with no width, and nothing happens at all — the box is already the full width of the page, so there is nothing left over to share. 给一个没有设宽度的盒子写 margin: 0 auto,什么也不会发生—— 盒子本来就和页面一样宽,根本没有剩下的空间可以平分。
Set the width first, then centre it. 先设宽度,再居中。
In that order it works every time, and out of order it looks like the property is broken. 按这个顺序,每次都成立;顺序反了,就会觉得这个属性坏掉了。
Four things to take with you. 带走四点。
One: a block box fills the page until you set a width. 第一:块级盒子会占满页面,直到你给它设了宽度。
Two: max-width is kinder on a small screen. 第二:在小屏幕上,max-width 更友好。
Three: margin zero auto centres a box. 第三:margin: 0 auto 让盒子居中。
Four: auto needs a width, or there is nothing to share. 第四:auto 需要一个宽度,否则没有可以平分的空间。
Now set the width, then centre the card. 现在先设宽度,再把卡片居中。

Log in or create account

IGCSE, A-Level & AP