CSS selectors are patterns used to select and style HTML elements. They are a fundamental part of CSS, enabling developers to apply styles to specific elements or groups of elements. Here is a detailed overview of various types of CSS selectors:
*{ color: red; }
p {
font-size: 16px;
}
.
) followed by the class name..button {
background-color: blue;
}
#
) followed by the ID name.#header {
background-color: green;
}
/* Selects all input elements with a type attribute equal to "text" */
input[type="text"] {
border: 1px solid #ccc;
}
/* Selects all <span> elements inside <div> elements */
div span {
color: red;
}
/* Selects all <p> elements that are direct children of <div> elements */
div > p {
margin: 0;
}
/* Selects the first <p> element that is immediately preceded by an <h1> element */
h1 + p {
font-weight: bold;
}
/* Selects all <p> elements that are siblings of an <h1> element */
h1 ~ p {
color: blue;
}
a:hover {
text-decoration: underline;
}
input:focus {
outline: none;
border: 2px solid blue;
}
/* Selects every second <li> element */
li:nth-child(2n) {
background-color: lightgray;
}
p::before {
content: "Note: ";
font-weight: bold;
}
p::after {
content: " (end)";
}
/* Applies the same styles to <h1> and <h2> elements */
h1, h2 {
font-family: Arial, sans-serif;
}
[attribute]: Selects elements with a specific attribute.
/* Selects all elements with a title attribute */
[title] {
border-bottom: 1px dotted black;
}
Selects elements with a specific attribute value.
/* Selects all input elements with type="radio" */
input[type="radio"] {
margin: 10px;
}
Selects elements with an attribute containing a specified word.
/* Selects elements with a class attribute containing the word "note" */
[class~="note"] {
background-color: yellow;
}
Selects elements with an attribute value either exactly equal to a specified value or starting with the specified value followed by a hyphen.
/* Selects elements with a lang attribute equal to "en" or starting with "en-" */
[lang|="en"] {
color: green;
}
Selects the first child of a parent.
/* Selects the first <li> element in any list */
li:first-child {
font-weight: bold;
}
Selects the last child of a parent.
/* Selects the last <li> element in any list */
li:last-child {
font-style: italic;
}
Selects elements of a specific type based on their position.
/* Selects the second <p> element of its parent */
p:nth-of-type(2) {
color: red;
}
Selects an element that is the only child of its parent.
/* Selects any <p> element that is the only child of its parent */
p:only-child {
font-size: larger;
}