Thuộc tính margin là shorthand đặt cùng lúc 4 lề: top, right, bottom, left (theo chiều kim đồng hồ).
Ví dụ minh họa
Nhấn nút đặt 4 lề: top=30px, right=20px, bottom=40px, left=40px:
<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="display()">Đặt 4 lề</button>
<p id="myID">Đây là văn bản demo.</p>
<script>
function display() {
document.getElementById("myID").style.margin = "30px 20px 40px 40px";
}
</script>
</body>
</html>
Cú pháp margin shorthand
| Số giá trị | Cú pháp | Ý nghĩa |
|---|---|---|
| 1 | margin: 10px | 4 lề = 10px |
| 2 | margin: 10px 20px | top/bottom=10px, left/right=20px |
| 3 | margin: 10px 20px 30px | top=10, left/right=20, bottom=30 |
| 4 | margin: 10px 20px 30px 40px | top=10, right=20, bottom=30, left=40 |
Giá trị auto – Căn giữa block
element.style.margin = "0 auto"; // top/bottom=0, left/right=auto → căn giữa ngang
Yêu cầu: phần tử có width xác định và display: block (hoặc table, flex, grid).