เรียนรู้วิธีใช้งาน Element <style> ใน HTML
Element <style> ใช้สำหรับฝังสไตล์ (CSS) โดยตรงเข้าไปในเอกสาร HTML ของคุณ:
<style> h1 { color: red; } p { color: green; } </style>
Element <style> จะต้องอยู่ภายใน Element <head> ของเอกสาร HTML:
<!DOCTYPE html> <html> <head> <style> h1 { color: red; } p { color: green; } </style> </head> <body> <h1>This is a red heading</h1> <p>This is a green paragraph</p> </body> </html>
คุณยังสามารถนำเข้าไฟล์สไตล์ชีตภายนอกได้ ซึ่งทำผ่าน Element <link> วิธีนี้เป็นวิธีที่ แนะนำ โดยเฉพาะสำหรับเว็บไซต์ขนาดใหญ่
ข้อมูลที่ควรทราบ:
หากคุณใช้ทั้ง <style> และ <link> ในการจัดสไตล์เอกสารเดียวกัน จะง่ายมากที่จะทับซ้อนสไตล์โดยไม่ได้ตั้งใจ
ตัวอย่างเช่น โค้ดด้านล่างใช้ทั้งสองวิธี:
<!DOCTYPE html> <html> <head> <!-- Embedded (internal) styles --> <style> h1 { color: red; } p { color: green; } </style> <!-- Import external style sheet --> <link href="/styles/main.css" rel="stylesheet" /> </head> <body> <h1>This is a red heading</h1> <p>This is a green paragraph</p> </body> </html>
ดังนั้น หากไฟล์สไตล์ชีตภายนอกกำหนดคุณสมบัติ color ให้กับ Selector h1 และ p เช่น ให้สีน้ำเงิน (blue) ค่าสีแดง (red) และสีเขียว (green) จะถูกทับซ้อน เพราะ Element <link> อยู่หลัง Element <style> ในมาร์กอัปข้างต้น
เรื่องนี้เกิดขึ้นง่ายมาก จึงแนะนำให้ใช้ Element <link> ในการนำเข้าสไตล์เป็นหลัก และใช้ <style> เฉพาะกรณีเฉพาะเจาะจงเท่านั้น