Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

วิธีใช้ Inline CSS (Inline Style) ใน HTML

Inline CSS คือการเขียน CSS โดยตรงใน attribute style ของ element ใช้สำหรับ style เฉพาะ element นั้นๆ เท่านั้น

รูปแบบ

<h1 style="color: red; font-size: 24px; text-align: center;">Heading</h1>

ตัวอย่าง

<!DOCTYPE html>
<html>
<head>
  <title>HTML Inline CSS</title>
</head>
<body>
  <h1 style="font-size: 20px;">Tutorials</h1>
  <p style="color: #333; line-height: 1.6;">We have tutorials on Programming, CMS, Scripting Languages, etc.</p>
</body>
</html>

CSS Properties ที่ใช้บ่อย

Propertyตัวอย่าง
colorcolor: red; / color: #ff0000;
font-sizefont-size: 16px;
font-familyfont-family: Arial, sans-serif;
text-aligntext-align: center;
background-colorbackground-color: #f0f0f0;
margin / paddingmargin: 10px; padding: 20px;
displaydisplay: none; display: flex;

ข้อดี/ข้อเสีย

ข้อดีข้อเสีย
Specificity สูงสุด (override ทุกอย่าง)ไม่ reuse ได้
ทดสอบเร็ว (quick testing)โค้ดยาว อ่านยาก บำรุงรักษายาก
เหมาะ dynamic styles (JS)แยก content กับ presentation ไม่ได้
Email HTML (รองรับดีที่สุด)Performance แย่ (ไม่ cache)

แนวทางปฏิบัติที่ดี

  • หลีกเลี่ยงใน production code ใช้ class + external CSS แทน
  • ใช้ได้: Email templates, Dynamic styles via JS, Quick prototyping
  • รวมหลาย property คั่นด้วย semicolon: style="prop1: val1; prop2: val2;"