เพื่อตั้งค่าสีพื้นหลังด้วย CSS ให้ใช้คุณสมบัติ background-color
ตัวอย่างที่ 1: background-color บน class
<!DOCTYPE html> <html> <head> <style> .demo { text-decoration: overline underline; background-color: red; } </style> </head> <body> <h1>Details</h1> <p class="demo">Examination Center near ABC College.</p> <p class="demo2">Exam begins at 9AM.</p> </body> </html>
ผลลัพธ์

ตัวอย่างที่ 2: background-color บน body (inline style)
<!DOCTYPE html> <html> <head> <style> .demo { text-decoration: overline underline; } </style> </head> <body style="background-color: orange; color: white;"> <h1>Details</h1> <p class="demo">Examination Center near ABC College.</p> <p class="demo2">Exam begins at 9AM.</p> </body> </html>
ผลลัพธ์

รูปแบบค่าสีที่ใช้ได้
/* Named colors */ background-color: red; background-color: transparent; /* ค่าเริ่มต้น */ /* Hex */ background-color: #ff0000; background-color: #f00; /* shorthand */ background-color: #ff000080; /* 8-digit hex (alpha) */ /* RGB/RGBA */ background-color: rgb(255, 0, 0); background-color: rgba(255, 0, 0, 0.5); /* HSL/HSLA */ background-color: hsl(0, 100%, 50%); background-color: hsla(0, 100%, 50%, 0.5); /* Modern syntax (space-separated) */ background-color: rgb(255 0 0 / 0.5); background-color: hsl(0 100% 50% / 50%);
คุณสมบัติพื้นหลังทั้งหมด (Shorthand)
background: color image repeat attachment position / size origin clip;
/* ตัวอย่าง */
background: #fff url('bg.jpg') no-repeat fixed center / cover padding-box border-box;
คำแนะนำ
- ตั้งค่า
background-colorสำรอง (fallback) เมื่อใช้ background-image เผื่อภาพโหลดไม่สำเร็จ - ใช้
transparentเพื่อทำให้โปร่งใส - สำหรับ gradient ใช้
background-image: linear-gradient(...)ไม่ใช่ background-color