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

CSS Selector เลือกองค์ประกอบที่ไม่มีคลาส/แอตทริบิวต์/ประเภทเฉพาะ


ใช้ pseudo-class :not() ของ CSS เพื่อคัดเลือกองค์ประกอบที่ไม่ตรงกับเงื่อนไขที่กำหนด

ตัวอย่างที่ 1: เลือก <p> ที่ไม่ได้อยู่ใน <div>

<!DOCTYPE html> <html> <head> <style> p {    background-color: cornflowerblue;    color: white; } p:not(div>p) {    background-color: khaki;    font-size: 1.4em;    font-style: italic;    color: blue; } </style> </head> <body> <div> <p>Curabitur sapien diam, imperdiet ut est sed, blandit blandit velit. Nunc viverra nunc id ligula ultricies, a fringilla lacus interdum. <span>Sed vel diam at magna pellentesque porttitor.</span> </p> <h3>Demo</h3> </div> <p> Ut rutrum sapien sit amet sapien lacinia, at ullamcorper felis lobortis. Praesent dignissim vel turpis nec ultricies.</p> </body> </html>

ตัวอย่างที่ 2: เลือก <div> ที่ไม่มีคลาส .parent

<!DOCTYPE html> <html> <head> <style> div {    margin: 2%;    background-color: cadetblue;    padding: 10%;    height: 80px; } div:not(.parent) {    box-shadow: inset 0 0 24px tomato;    padding: 2%; } .parent{    border: 4px ridge orange; } .one {    background-color: lightgreen;    border: 4px groove gray; } .two{    height: 20px; } </style> </head> <body> <div class="parent"> <div class="one"> <div class="two"></div> <div class="two"></div> </div> <div class="one"></div> </div> </body> </html>

Selector :not() สามารถรับ selector ย่อยได้ เช่น :not(.class), :not([attribute]), :not(tag), :not(:pseudo-class) ทำให้สามารถกรององค์ประกอบได้อย่างยืดหยุ่น