Panduan lengkap CSS Advanced Selectors untuk seleksi elemen yang lebih presisi
Advanced Selectors memungkinkan Anda memilih elemen dengan lebih spesifik berdasarkan hubungan, atribut, atau kondisi tertentu.
/* Attribute Selector */
input[type="text"] {
border: 2px solid #9333ea;
}
/* Child Combinator */
ul > li {
list-style-type: none;
}
/* General Sibling */
h2 ~ p {
color: #a855f7;
}
đ Penjelasan Detail:
âĸ [attribute]
- Memilih elemen berdasarkan atribut
âĸ >
- Child combinator memilih elemen anak langsung
âĸ ~
- General sibling memilih semua saudara berikutnya
âĸ +
- Adjacent sibling memilih saudara berikutnya langsung
/* Attribute Starts With */
a[href^="https"] {
color: #4CAF50;
}
/* Attribute Ends With */
a[href$=".pdf"] {
background: url('pdf-icon.png');
}
/* Attribute Contains */
img[src*="logo"] {
border: 1px solid #9333ea;
}
Attribute Selectors didukung penuh di Chrome 1+, Firefox 1+, Safari 3+, IE 7+. Advanced selectors bekerja di semua browser modern.
/* Descendant Selector */
.container p {
color: #e0e0e0;
}
/* Child Selector */
nav > ul {
padding-left: 0;
}
/* Adjacent Sibling */
h2 + p {
margin-top: 0;
}
/* General Sibling */
h2 ~ p {
font-weight: bold;
}
đ Penjelasan Detail:
âĸ A B
- Memilih semua B yang merupakan keturunan A
âĸ A > B
- Memilih B yang merupakan anak langsung A
âĸ A + B
- Memilih B yang langsung mengikuti A
âĸ A ~ B
- Memilih semua B yang mengikuti A (saudara)
/* Structural Pseudo-classes */
li:nth-child(2n+1) {
background: rgba(147, 51, 234, 0.1);
}
tr:nth-of-type(even) {
background: #f5f5f5;
}
p:first-of-type {
font-weight: bold;
}
:not(.ignore) {
opacity: 0.9;
}
Structural pseudo-classes: Chrome 1+, Firefox 3.5+, Safari 3.1+, IE 9+. :not() selector: Chrome 1+, Firefox 3.5+, Safari 3.1+, IE 9+.
Gunakan advanced selectors untuk membuat CSS Anda lebih efisien dan maintainable, tetapi hindari kompleksitas yang tidak perlu.
/* â
Good - Specific but readable */
nav[role="main"] > ul > li > a {
color: #9333ea;
}
/* â
Good - Using :where() for lower specificity */
:where(section, article) h2 {
font-size: 1.8rem;
}
/* â Avoid - Too complex */
body > div:first-child > main > section:nth-of-type(3) > div > p:first-of-type {
color: red;
}
đ Penjelasan Detail:
âĸ Prioritaskan readability - Selector harus mudah dipahami
âĸ Gunakan :where() - Untuk mengurangi specificity ketika memungkinkan
âĸ Hindari over-qualifying - Jangan membuat rantai selector yang terlalu panjang
âĸ Manfaatkan attribute selectors - Untuk seleksi berbasis atribut yang fleksibel