คุณสมบัติ padding เป็น shorthand สำหรับกำหนด padding-top, padding-right, padding-bottom, padding-left พร้อมกัน
รูปแบบค่า (1-4 ค่า)
/* 1 ค่า */ padding: 10px; /* ทุกด้าน */ /* 2 ค่า */ padding: 10px 5px; /* top/bottom, left/right */ /* 3 ค่า */ padding: 10px 5px 7px; /* top, left/right, bottom */ /* 4 ค่า */ padding: 10px 5px 7px 10px; /* top, right, bottom, left (ตามเข็มนาฬิกา) */
ตัวอย่างที่ 1: Padding แบบเปอร์เซ็นต์และ Nested Div
<!DOCTYPE html> <html> <head> <style> div { height: 150px; width: 300px; padding: 5% 10% 20% 5%; background-image: url("https://www.tutorialspoint.com/images/home_tensor_flow.png"); text-align: center; font-weight: bold; font-size: 1.2em; box-sizing: border-box; } div > div { border-radius: 80px; padding: 2em 2em; box-shadow: 0 0 4px 0.8px black; } </style> </head> <body> <div>Learn TensorFlow <div>TensorFlow is an open source machine learning framework for all developers.</div> </div> </body> </html>
ตัวอย่างที่ 2: Padding กับ Box-sizing และ Nested Elements
<!DOCTYPE html> <html> <head> <style> div { height: 150px; width: 100px; padding: 5% 1%; background-color: papayawhip; border-radius: 5%; box-sizing: border-box; } div > div { width: 50px; height: 50px; border-radius: 50%; padding: 2em; box-shadow: 0 0 9px 1px black; } span { padding: 10px; } </style> </head> <body> <div> <div></div> <span><i>button</i></span> </div> </body> </html>
คำอธิบาย
ตัวอย่างที่ 1: div ภายนอก padding 5% top, 10% right, 20% bottom, 5% left (เปอร์เซ็นต์ของ width) ใช้ box-sizing: border-box ทำให้ padding รวมอยู่ใน width/height
ตัวอย่างที่ 2: div ภายนอก padding 5% top/bottom, 1% left/right div ภายในเป็นวงกลม padding 2em span padding 10px ทั้ง 4 ด้าน
Box-sizing สำคัญ:
content-box(ค่าเริ่มต้น) - width/height = content เท่านั้น padding/border เพิ่มขนาดborder-box- width/height = content + padding + border (แนะนำใช้ global)
*, *::before, *::after { box-sizing: border-box; }
Logical Properties (ใหม่):
padding-block-start: 10px; /* top ใน LTR */ padding-inline-end: 20px; /* right ใน LTR */ padding-block-end: 15px; /* bottom ใน LTR */ padding-inline-start: 5px; /* left ใน LTR */ /* Shorthand */ padding-block: 10px 15px; /* top, bottom */ padding-inline: 5px 20px; /* left, right */