Width and centering · 宽度与居中
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
Width
- By default, a block box is as wide as the page.
width: 300px;makes it a fixed width instead.max-width: 600px;is gentler — at most this wide, but shrink on small screens.
中文
宽度
- 默认情况下,块级盒子会和页面一样宽。
width: 300px;让它改成固定宽度。max-width: 600px;更温和 —— 最多这么宽,屏幕小的时候会自动缩小。
English
Centering a box
- To center a box (not just its text), give it a width, then
margin: 0 auto;. 0 automeans no top/bottom margin, and equal left/right margins.- Equal side margins push the box into the middle.
中文
让盒子居中
- 要让一个盒子居中(不只是里面的文字),先给它一个宽度,再写
margin: 0 auto;。 0 auto表示:上下没有外边距,左右外边距相等。- 两边相等的外边距,就把盒子推到了中间。
<style>
.card {
width: 280px;
margin: 0 auto;
padding: 16px;
background-color: #eef;
}
</style>
<div class="card">A centered card.</div>
English
Common mistakes
- Centre a block with a set width using
margin: 0 auto. - A width in
%is relative to the parent element.
中文
常见错误
- 给设定宽度的块用
margin: 0 auto居中。 - 以
%为单位的宽度相对于父元素。
English
Now you try
- A box needs a width before
margin: 0 auto;can center it. - Set a width, then center the card.
中文
现在你来试试
- 盒子要先有宽度,
margin: 0 auto;才能让它居中。 - 先设宽度,再把卡片居中。
Explore · 探索
Width and the box · 宽度与盒子
Width sets the content size; padding/border/margin add around it. · width 设置内容大小;padding/border/margin 在外面叠加。
Give the card a fixed width. Add width: 300px; to the .card rule. · 给卡片一个固定宽度。在 .card 规则里加上 width: 300px;。
Center the card on the page. Add margin: 0 auto; to the .card rule. · 把卡片在页面上居中。在 .card 规则里加上 margin: 0 auto;。