CSS selectors are powerful tools that allow you to target specific HTML elements and apply styles. This guide will provide an in-depth reference, from basic selectors to advanced ones, ensuring you have a comprehensive understanding.
Targets all elements on the page.
* {
margin: 0;
padding: 0;
}
Targets specific HTML elements.
p {
color: blue;
}
Targets elements with a specific class.
.highlight {
background-color: yellow;
}
Targets a specific element with a unique ID.
#header {
font-size: 24px;
}
Targets elements with a specific attribute.
[target] {
text-decoration: underline;
}
Targets elements with a specific attribute value.
[type="submit"] {
background-color: green;
}
Targets elements with an attribute starting with a specific value.
[href^="https"] {
color: blue;
}
Targets nested elements.
article p {
font-style: italic;
}
Targets direct children of an element.
ul > li {
list-style-type: square;
}
Targets an element that is immediately preceded by a specified element.
h2 + p {
font-weight: bold;
}
Targets an element when the user hovers over it.
a:hover {
color: red;
}
Targets elements based on their position.
li:nth-child(odd) {
background-color: #f2f2f2;
}
Adds content before or after the selected element.
p::before {
content: "» ";
}
Styles the first line or first letter of an element.
p::first-line {
font-weight: bold;
}
Excludes elements from the selection.
li:not(.special) {
color: gray;
}
Targets an element if any of its descendants have focus.
form:focus-within {
border: 2px solid blue;
}
This CSS Selectors Reference covers a wide range of selectors, from the fundamental to advanced. By mastering these, you can precisely target and style elements in your web pages. Use this guide as a comprehensive resource to enhance your CSS skills and create well-styled, dynamic web designs. Happy coding! ❤️