Could we help you? Please click the banners. We are young and desperately need the money
CSS is a powerful tool for styling web pages, but beyond the commonly known selectors like class, id, and :nth-child, there are advanced selectors and features that can greatly enhance your workflow. Whether you're a junior developer looking to level up or a seasoned professional exploring new tricks, this guide covers some of the most useful and lesser-known CSS selectors.
The :has() pseudo-class allows you to style a parent element based on the presence of a specific child element. This was previously difficult to achieve with CSS alone.
article:has(img) {
border: 2px solid blue;
}
This will apply a border to any <article> element that contains an <img> inside.
The :is() selector lets you group selectors efficiently, reducing redundancy.
:is(h1, h2, h3) {
color: darkblue;
}
This applies the same style to all headers without repeating the rule for each one.
The :where() selector works like :is() but does not increase specificity, making it easier to override.
:where(h1, h2, h3) {
margin-bottom: 10px;
}
Since :where() has zero specificity, other styles can override it easily.
Unlike :nth-child(), which counts all child elements, :nth-of-type() targets a specific element type.
p:nth-of-type(2) {
color: red;
}
This targets the second <p> within its parent, regardless of other elements present.
The :not() selector lets you exclude elements from styling.
button:not(.primary) {
background: gray;
}
All buttons except those with the .primary class will get a gray background.
CSS provides powerful attribute selectors that go beyond class and ID targeting.
input[type="text"] {
border: 1px solid black;
}
This applies styles only to text inputs.
a[href^="https"] {
color: green;
}
This targets links starting with "https".
You can style list bullets or numbers directly using ::marker.
li::marker {
color: red;
font-size: 20px;
}
This makes list markers red and larger.
Container queries enable the application of styles based on the size of a container (parent element) rather than the viewport size. This helps in creating responsive layouts within a specific container.
.container {
width: 100%;
container-type: inline-size;
}
@container (min-width: 400px) {
.item {
background-color: lightgreen;
}
}
@container (min-width: 600px) {
.item {
background-color: lightblue;
}
}
In the example above, .item changes its background color depending on the size of the .container. The @container query lets us apply styles based on the container's width, not the viewport width.
By mastering these special CSS selectors, you can write cleaner, more efficient, and more powerful styles. These techniques improve maintainability and provide better control over web page styling. Start experimenting with these selectors today and elevate your front-end development skills!