selector ใน css มีหลายแบบ แต่จะแนะนำอันหลัก ๆ ดังนี้
- Descendant Selector
- Parent-Child Selector
- Adjacent Selector
- Attribute Selector
โดยจะขออธิบายทีละอย่าง เริ่มกันเลย
1. Descendant Selector
Descentdant แปลโดย พจนานุกรม Longdo แปลว่า “ซึ่งสืบทอดมา”, “ผู้สืบสกุล”, “ทายาท” ซึ่งก็คือ การสืบทอดนั่นเองโดยมีตัวอย่างการใช้ดังนี้
CSS:
li em {
color: green;
}
แบบนี้จะเลือกทุก ๆ em ที่อยู่ภายใต้ li โดยเลือกทั้งหมดไม่ว่า em จะซ้อนด้วยแท็กอื่นอีกที ขอแค่ให้มี li ครอบอยู่ก่อนหน้านั้น
ใน HTML ข้างล่าง em ตัวแรกจะแสดงผลเป็นสีเขียว แต่ em ตัวที่สองจะเป็นสีปกติ
HTML:
<ul> <li>Item One</li> <li>Item <em>two</em></li> </ul> <p>An <em>italicized</em> words.</p>
2. Parent-Child Selector
มีตัวอย่างการใช้งาน ดังนี้
CSS:
body > p {
font-weight: bold;
}
แบบนี้จะเลือกเฉพาะ p ที่เป็น element ลูกโดยตรงของ body ไม่นับพวกที่โดนซ้อนอยู่อีกโดย tag อื่น
จาก HTML ข้างล่าง p ตัวที่ไม่อยู่ใน block ของ element ในที่นี้คือ <p id=”para2″>จะแสดงผลเป็นตัวหนา เพราะอยู่ติดกับ body แต่ p ตัวที่สองจะเป็นเป็นขนาดปกติ
HTML:
<body> <div class="sidebar"> <p id="para1">This is the sidebar.</p> </div> <p id="para2">Welcome to the web site! Here's a list</p> <ul> <li> <p id="para3">This is the first paragraph in the list. It's also the last.</p> </li> </ul> </body>
การใช้ Parent-Child Selector ไม่รองรับกับ Internet Explorer 6 ดังนั้นก็แล้วแต่เป้าหมายของผู้ชมกลุ่มเป้าหมายละกาน
3. Adjacent Selector
Adjacent Selector เป็น selector ที่ไม่ใช้การสืบทอดเหมือนกับ Descendant Selector แต่เป็นตัวที่ติดกันในโค๊ด HTML ดังตัวอย่างด้านล่าง
CSS:
h1+h2 {
margin-top: 11px;
}
จากตัวอย่างเป็นการบอกให้ h2 ตัวแรกที่อยู่ติดกับ h1 มีช่องว่างด้านบน 11 px โดยดูตัวอย่างจาก HTML ดังนี้
<h1>This is important stuff!</h1> <h2>First important item</h2> <h2>Second important item</h2>
จาก HTML แท็ก h2 บรรทัดที่ 2 จะห่างจาก h1 ขนาด 11 px แต่จะไม่มีผลกับ h2 ในบรรทัดที่สาม
และอีกตามเคย ไม่ support Internet Explorer 6
4. Attribute Selectors
selector แบบที่ 4 นี้จะคล้ายกับการเขียนโปรแกรม โดยมีรูปแบบดังนี้
[attribute] จะเข้าเงื่อนไขคือกำหนด attribute ทั้งหมด
[attribute="value"] จะเข้าเงื่อนไขเมื่อมีการกำหนดค่าให้กับ attribute
[attribute~="value"] คือ attribute ใด ๆ ที่มีคำตรงกับค่าที่กำหนด จากการเว้นช่องว่าง
[attribute|="value"] คือ attribute ใด ๆ ที่มีคำตรงกับค่าที่กำหนด โดยใช้เครื่องหมายคำพูด
ตัวอย่างการใช้งาน ถ้าต้องการให้ textbox (<input type=”text” />) มีตัวอักษรสีขาว และพื้นหลังเป็นสีดำ สามารถกำหนด CSS ดังนี้
input[type="text"] {
color: white;
background-color: black;
}
อีกซักตัวอย่าง
CSS:
div[class~="advertisement"] {
background: rgb(220, 220, 220);
width: 74em;
border: solid 0.02em rgb(200, 200, 200);
margin: 0 auto;
min-height: 5em;
}
HTML:
<div class="Advertisement promotion banner"> <p>Content goes here</p> </div>
แค่นี้แหละ ขี้เกียจแระ