Complex selectors allow you to target specific elements based on their relationship with other elements.
/* Descendant selector */
.container p {
color: red;
}
/* Child selector */
.container > p {
color: green;
}
/* Adjacent sibling selector */
h1 + p {
color: blue;
}
/* General sibling selector */
h1 ~ p {
color: orange;
}
This is a descendant paragraph.
This is a child paragraph.
This paragraph follows the h1.
This is another sibling paragraph.
Attribute selectors allow you to select elements based on their attributes and attribute values.
/* Selects input elements with a type of "text" */
input[type="text"] {
border: 2px solid blue;
}
/* Selects links that have the class "external" */
a[class="external"] {
color: red;
}
These pseudo-classes allow you to select specific child elements based on their position in the parent.
/* Select the 2nd child of any parent */
li:nth-child(2) {
color: green;
}
/* Select all odd list items */
li:nth-child(odd) {
background-color: lightgray;
}
/* Select the 1st 'p' element */
p:nth-of-type(1) {
font-size: 20px;
}
This is the first paragraph.
This is the second paragraph.
The :not() selector targets elements that do not match a given selector.
/* Select all paragraphs except those with the class 'highlight' */
p:not(.highlight) {
color: blue;
}
This paragraph is blue.
This paragraph is not blue.
CSS variables allow you to store values that can be reused throughout the stylesheet.
/* Define a CSS variable */
:root {
--main-color: #3498db;
}
/* Use the variable */
h1 {
color: var(--main-color);
}
p {
color: var(--main-color);
}
This paragraph uses the same color as the heading.
The calc() function allows you to perform calculations for property values, combining units like px, %, and em.
/* Set width to 50% minus 20px */
div {
width: calc(50% - 20px);
background-color: #f4f4f4;
height: 100px;
}
These functions allow you to set dynamic values that adapt based on different conditions.
/* Set width to the smaller value of 300px or 50% */
div {
width: min(300px, 50%);
background-color: #8e44ad;
height: 100px;
}
/* Set width to the larger value of 200px or 50% */
section {
width: max(200px, 50%);
background-color: #e74c3c;
height: 100px;
}
/* Clamp width between 100px and 400px, with a default of 50% */
article {
width: clamp(100px, 50%, 400px);
background-color: #2ecc71;
height: 100px;
}