Width and centering · Chiều rộng và căn giữa
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · Trang này cần trình duyệt gần đây (hỗ trợ SharedArrayBuffer). Vui lòng cập nhật Chrome, Edge, Firefox hoặc Safari lên phiên bản mới nhất.
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.
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.
<style>
.card {
width: 280px;
margin: 0 auto;
padding: 16px;
background-color: #eef;
}
</style>
<div class="card">A centered card.</div>
Common mistakes
- Centre a block with a set width using
margin: 0 auto. - A width in
%is relative to the parent element.
Now you try
- A box needs a width before
margin: 0 auto;can center it. - Set a width, then center the card.
Explore · Khám phá
Width and the box · Chiều rộng và hộp
Width sets the content size; padding/border/margin add around it. · Chiều rộng xác định kích thước nội dung; padding/border/margin bổ sung xung quanh.
Give the card a fixed width. Add width: 300px; to the .card rule. · Gán chiều rộng cố định cho thẻ. Thêm width: 300px; vào quy tắc .card.
Center the card on the page. Add margin: 0 auto; to the .card rule. · căn giữa thẻ trên trang. Thêm margin: 0 auto; vào quy tắc .card.