Thuộc tính CSS margin là shorthand cho margin-top, margin-right, margin-bottom, và margin-left. Nó cho phép chúng ta chỉ định khoảng cách xung quanh các phần tử. Chúng ta cũng có thể đặt margin cho từng cạnh riêng lẻ.
Cú pháp
Selector {
margin: /*value*/
}
Ví dụ 1: Margin shorthand với 3 giá trị
<!DOCTYPE html>
<html>
<head>
<style>
div { margin: 10px 50px 20px; padding: 1rem; border: dashed; }
p { text-align: center; }
#demo { margin-left: -80px; box-shadow: inset 0 0 10px brown; }
</style>
</head>
<body>
<div></div>
<p>This is demo text.</p>
<p id="demo">Another demo text.</p>
<p>This is new demo text.</p>
</body>
</html>
Kết quả

Ví dụ 2: Margin tự động và margin âm
<!DOCTYPE html>
<html>
<head>
<style>
ul { margin: auto; background-image: linear-gradient(to right, khaki, aliceblue, skyblue, rebeccapurple); width: 20em; }
li { margin-top: 3px; }
li + li { margin-left: -20px; }
li:last-child { margin-left: 75px; }
</style>
</head>
<body>
<h2>Demo Heading</h2>
<ul>
<li>This is demo list item.</li>
<li>This is another list item with different style.</li>
<li>This is our third demo text with another style. </li>
</ul>
</body>
</html>
Kết quả

Margin shorthand patterns:
margin: 10px;- 4 cạnh = 10pxmargin: 10px 20px;- top/bottom = 10px, left/right = 20pxmargin: 10px 20px 30px;- top = 10px, left/right = 20px, bottom = 30pxmargin: 10px 20px 30px 40px;- top, right, bottom, left (theo chiều kim đồng hồ)
Đặc điểm quan trọng:
- Margin collapsing (gộp margin): Vertical margins của các block elements liền kề sẽ gộp lại (lấy giá trị lớn hơn), KHÔNG cộng dồn. Không xảy ra cho flex/grid items, absolute/fixed elements, hoặc có padding/border/clear.
- Margin âm: Kéo phần tử ra ngoài, overlap với element khác, hoặc căn giữa (margin: auto)
- Margin auto: Căn giữa block element ngang (cần width xác định), không hoạt động cho vertical trừ khi dùng flexbox/grid
- Margin %: Tính theo width của containing block (cả top/bottom), không phải height