เรียนรู้วิธีใช้ CSS shorthand properties เพื่อให้ stylesheets ของคุณใช้พื้นที่น้อยลง
CSS shorthand properties ให้คุณเขียนน้อยลงแต่ทำได้มากขึ้น
สมมติคุณอยาก style h1 element ด้วย font-family Georgia, font-size 42 pixels, และ line-height 1.25
มาดู normal CSS method ก่อน:
h1 {
font-family: "Georgia", "serif";
font-size: 42px;
line-height: 1.25;
}
เปรียบเทียบกับ CSS font shorthand method:
h1 {
font: 42px/1.25 "Georgia", "serif";
}
สามบรรทัดกลายเป็นหนึ่งบรรทัด!
Shorthand properties ทำงานโดยรวม several style declarations เป็นบรรทัดเดียว และให้ code ใช้พื้นที่น้อยลง
Shorthand code อาจไม่อ่านง่ายเท่า regular method ที่ expressive กว่านั้น แต่เพราะมันใหม่ จะกลายเป็น second nature ไวๆ ถ้าคุณเริ่มใช้
มาดูอีกตัวอย่าง shorthand CSS property:
นี่คือ button ที่มี top และ bottom padding 12px, left และ right padding 20px:
ใช้ padding properties ต่อไปนี้:
button {
padding-top: 12px;
padding-right: 20px;
padding-bottom: 12px;
padding-left: 20px;
}
ตอนนี้ใช้ shorthand padding property ทำให้ CSS น้อยลง:
button {
padding: 12px 20px; /* top-bottom, left-right */
}
สี่บรรทัดกลายเป็นหนึ่งบรรทัด!
padding shorthand ข้างต้นเรียกว่า two-value shorthand เพราะใช้สองค่า
- ค่าแรก
12pxตรงกับpadding-topและpadding-bottom - ค่า
20pxตรงกับpadding-leftและpadding-right
รายชื่อ shorthand properties ใน CSS ทั้งหมด:
all, animation, background, border, border-block-end, border-block-start, border-bottom, border-color, border-image, border-inline-end, border-inline-start, border-left, border-radius, border-right, border-style, border-top, border-width, column-rule, columns, flex, flex-flow, font, gap, grid, grid-area, grid-column, grid-row, grid-template, list-style, margin, mask, offset, outline, overflow, padding, place-content, place-items, place-self, scroll-margin, scroll-padding, text-decoration, text-emphasis, transition.
ดู Mozilla's complete CSS shorthand docs
ไม่ใช่ shorthand properties ทั้งหมดที่คุ้มค่าจำ เพราะโอกาสน้อยที่คุณจะใช้ แต่ shorthand สองตัวอย่างจาก tutorial นี้ font และ padding เป็นที่ใช้บ่อยที่สุด
Shorthand properties ต่อไปนี้ก็ worth looking into (เพราะคุณจะใช้บ่อย) margin, background, border, animation, transition, border-radius