การรวม CSS ใน HTML สามารถทำได้ 3 วิธี ได้แก่ Inline, Internal และ External
ไวยากรณ์ (Syntax)
/* Inline */
<element style="/*declarations*/"></element>
/* Internal */
<head>
<style> /*declarations*/ </style>
</head>
/* External */
<head>
<link rel="stylesheet" href="#location">
</head>
ตัวอย่างที่ 1: Inline CSS
<!DOCTYPE html>
<html>
<head></head>
<body>
<p style="font-family: Forte;">Demo text</p>
<p style="background-color: lightblue;">This is Demo text</p>
<img src="https://www.tutorialspoint.com/memcached/images/memcached.jpg" style="border: 3px groove orange;">
</body>
</html>
ผลลัพธ์

ตัวอย่างที่ 2: Internal CSS (ใน <head>)
<!DOCTYPE html>
<html>
<head>
<style>
div { margin: auto; padding: 15px; width: 33%; border: 2px solid; border-radius: 5%; }
div > div { border-color: transparent; box-shadow: inset 0 0 6px red; }
div > div > div { border-color: red; }
</style>
</head>
<body>
<div>
<div></div>
<div> <div></div> </div>
<div></div>
</div>
</body>
</html>
ผลลัพธ์

ตัวอย่างที่ 3: External CSS (ไฟล์แยก)
HTML file:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<p>Demo text</p>
<p>Demo text again</p>
</body>
</html>
CSS file (style.css):
p {
text-decoration: overline;
text-transform: capitalize;
}
ผลลัพธ์

เปรียบเทียบ 3 วิธี
| วิธี | ข้อดี | ข้อเสีย | เหมาะสำหรับ |
|---|---|---|---|
| Inline | เร็วที่สุด สำหรับทดสอบ | ซ้ำซ้อน ไม่แยก concerns ยากต่อการบำรุงรักษา | ทดสอบด่วน Email template |
| Internal | แยก HTML/CSS ในไฟล์เดียว | ใช้ซ้ำไม่ได้ระหว่างหน้า | หน้าเดียว (Single page) |
| External | ใช้ซ้ำได้หลายหน้า Cache ได้ บำรุงรักษาง่าย | HTTP request เพิ่ม (แก้ได้ด้วย bundling) | เว็บไซต์จริง Production |