หลอกคลาส
Pseudo-classes ให้คุณเลือกสถานะหรือตำแหน่งเฉพาะขององค์ประกอบได้ ตัวอย่างเช่น :hover เลือกองค์ประกอบเมื่อตัวชี้เมาส์อยู่เหนือ :focus องค์ประกอบ เลือกองค์ประกอบเมื่อเลือกหรือมีโฟกัส :nth-child() เลือกองค์ประกอบย่อยเฉพาะในกลุ่ม
ตัวอย่าง:
/* Select all links when hovered over and change the text color */
a:hover {
color: red;
}
/* Select the <input> element when it is focused and change the border */
input:focus {
border: 2px solid blue;
}
/* Select the second element in a group of <li> elements and change the text color */
li:nth-child(2) {
color: green;
}
องค์ประกอบหลอก
องค์ประกอบเสมือนช่วยให้คุณสร้างองค์ประกอบเสมือนเพื่อปรับแต่งองค์ประกอบที่มีอยู่
ตัวอย่างเช่น ::before และ ::after สร้างองค์ประกอบก่อนและหลังองค์ประกอบ ::first-line และ ::first-letter เลือกบรรทัดแรกและตัวอักษรตัวแรกขององค์ประกอบ
ตัวอย่าง:
/* Add content before each <p> element and style it */
p::before {
content: ">> ";
font-weight: bold;
color: gray;
}
/* Style the first letter of <h1> element */
h1::first-letter {
font-size: 2em;
font-weight: bold;
color: red;
}
เครื่องผสม
Combinator ช่วยให้คุณสามารถรวมตัวเลือกเพื่อเลือกองค์ประกอบตามความสัมพันธ์ ตัวอย่างเช่น element1 element2 เลือก element2 ภายใน element1 เลือก element1 > element2 องค์ประกอบย่อยโดยตรง element1 ของ element1 + element2 เลือก element2 ทันที element1 หลังจาก
ตัวอย่าง:
/* Select <span> elements inside an element with class "container" */
.container span {
color: purple;
}
/* Select <li> elements that are direct children of <ul> */
ul > li {
list-style-type: square;
color: blue;
}
ตัวเลือกแอตทริบิวต์
ตัวเลือกแอตทริบิวต์ช่วยให้คุณเลือกองค์ประกอบตามค่าของแอตทริบิวต์ ตัวอย่างเช่น [attribute] เลือกองค์ประกอบที่มีแอตทริบิวต์ attribute เลือก องค์ประกอบที่ มี [attribute=value] แอตทริบิวต์ attribute เท่ากับ value เลือก [attribute^=value] องค์ประกอบที่มีแอตทริบิวต์ attribute เริ่มต้นด้วย value
ตัวอย่าง:
/* Select all elements with the attribute data-type */
[data-type] {
font-weight: bold;
color: orange;
}
/* Select all <a> elements with the href attribute starting with "https://" */
a[href^="https://"] {
color: blue;
text-decoration: underline;
}
:not() ตัวเลือก
ตัว เลือกอนุญาตให้คุณเลือกองค์ประกอบที่ไม่ตรงกับตัวเลือกเฉพาะ ตัวอย่างเช่น เลือกองค์ประกอบที่ไม่มีคลาส เลือก องค์ประกอบที่ไม่มี ID :not() :not(.class) class :not(#id) id
ตัวอย่าง:
/* Select all <div> elements that do not have the class "hidden" */
div:not(.hidden) {
display: block;
background-color: lightgray;
}
/* Select all <input> elements that do not have the ID "email-input" */
input:not(#email-input) {
border: 1px solid gray;
}
ตัวอย่างเหล่านี้แสดงให้เห็นถึงการเลือกองค์ประกอบขั้นสูงใน CSS คุณสามารถปรับแต่งและใช้เทคนิคเหล่านี้เพื่อจัดรูปแบบและปรับแต่งองค์ประกอบบนหน้าเว็บของคุณได้ตามต้องการ

