Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Định nghĩa nhiều style rule cho một element trong CSS

Một element có thể có nhiều property. Gom tất cả vào **một declaration block** của selector đó.

Cú pháp

selector {
  property1: value1;
  property2: value2;
  property3: value3;
  /* ... */
}

Ví dụ

h1 {
  color: #36C;
  font-weight: normal;
  letter-spacing: .4em;
  margin-bottom: 1em;
  text-transform: lowercase;
}

Quy tắc

  • Mỗi cặp property: value kết thúc bằng ;.
  • Cặp cuối cùng **nên** có ; (dễ bảo trì, thêm bớt).
  • Có thể viết một dòng hoặc nhiều dòng (khuyên nhiều dòng cho readability).
  • Thứ tự property không quan trọng (trừ shorthand property override longhand).

Shorthand vs Longhand

/* Shorthand - viết gọn */
margin: 10px 20px 15px 5px; /* top right bottom left */

/* Longhand - viết chi tiết */
margin-top: 10px;
margin-right: 20px;
margin-bottom: 15px;
margin-left: 5px;

/* Lưu ý: Shorthand reset các longhand không viết */
div { margin: 10px; } /* margin-top/right/bottom/left = 10px */
div { margin-top: 5px; margin: 10px; } /* margin-top = 10px (shorthand ghi đè) */

Best practice

  • Sắp xếp property theo nhóm: Layout → Box model → Visual → Typography → Misc.
  • Dùng tool format (Prettier, Stylelint) để nhất quán.