Advanced CSS Selectors (Attribute, Structural)

Introduction CSS selectors allow you to target HTML elements efficiently. While basic selectors (class, ID, tag) are common, advanced selectors help achieve precision and flexibility in styling. 1. Attribute Selectors Attribute selectors target elements based on attributes and values. Basic Attribute Selector Targets all <a> elements with a target attribute. Attribute Value Selector Targets links […]

  • Post author:
  • Post category: CSS
  • Reading time: 29 mins read
  • Post last modified: April 3, 2025

Introduction

CSS selectors allow you to target HTML elements efficiently. While basic selectors (class, ID, tag) are common, advanced selectors help achieve precision and flexibility in styling.

1. Attribute Selectors

Attribute selectors target elements based on attributes and values.

Basic Attribute Selector

a[target] {
    color: red;
}
CSS

Targets all <a> elements with a target attribute.

Attribute Value Selector

a[href="https://phpdev.in"] {
    font-weight: bold;
}
CSS

Targets links pointing to https://phpdev.in.

Partial Match Selectors

input[type^="text"] {
    background-color: lightgray;
}
CSS
  • ^=: Starts with
  • $=: Ends with
  • *=: Contains

2. Structural Pseudo-Classes

These selectors target elements based on position in the document tree.

:first-child & :last-child

p:first-child {
    color: blue;
}
p:last-child {
    color: green;
}
CSS

Targets the first and last <p> in a parent container.

:nth-child(n)

li:nth-child(odd) {
    background: lightblue;
}
CSS

Styles odd-numbered list items.

:nth-of-type(n)

div:nth-of-type(2) {
    font-size: 20px;
}
CSS

Targets the second <div> element among siblings.

3. UI Pseudo-Classes

These selectors respond to user interactions.

:focus

input:focus {
    border-color: orange;
}
CSS

Applies styles when an input field is focused.

:disabled

button:disabled {
    opacity: 0.5;
}
CSS

Styles disabled buttons.

Conclusion

Advanced CSS selectors provide powerful ways to target elements dynamically, improving efficiency and reducing reliance on extra classes or JavaScript.

Leave a Reply