This document is part of our Complete Guide to CSS (Outline).
1. Basic Selectors
Selectors are foundational in CSS, allowing you to target specific elements on a webpage to apply styles. The basic selectors include:
- Universal selector (
*
): Targets all elements on a page.
* {
margin: 0;
padding: 0;
}
- Type selectors (or tag selectors): Targets elements by their node name.
p {
font-size: 16px;
}
- Class selectors (
.classname
): Targets elements by their class attribute. These are especially useful when you want to style a specific group of elements without affecting others of the same type.
.highlight {
background-color: yellow;
}
- ID selectors (
#idname
): Targets a unique element by its ID attribute. Because IDs are unique, they should be used sparingly and only when necessary.
#header {
background-color: blue;
}
2. Combinator Selectors
Combinator selectors allow you to be more specific in which elements you target based on their relationships to others.
- Descendant selectors: Target elements that are descendants of another element.
article p {
color: gray;
}
- Child selectors (
>
): Target elements that are direct children of another.
ul > li {
list-style-type: square;
}
- General sibling selectors (
~
): Target elements that share the same parent.
h2 ~ p {
margin-top: 20px;
}
- Adjacent sibling selectors (
+
): Target an element immediately preceded by a specific element.
h2 + p {
text-indent: 1.5em;
}
3. Pseudo-class Selectors
Pseudo-classes let you apply styles based on state or position, rather than on identified elements.
- Interactive states:
a:hover {
text-decoration: underline;
}
button:active {
background-color: darkgray;
}
input:focus {
border-color: blue;
}
- Structural pseudo-classes:
p:first-child {
font-weight: bold;
}
li:nth-child(odd) {
background-color: lightgray;
}
4. Pseudo-element Selectors
Pseudo-elements allow you to style specific parts of an element’s content.
- Inserting content before and after elements:
p::before {
content: "Important: ";
font-weight: bold;
}
p::after {
content: " Read carefully.";
font-style: italic;
}
- Styling fragments of content:
p::first-line {
text-transform: uppercase;
}
p::first-letter {
font-size: 2em;
float: left;
}
5. Attribute Selectors
Attribute selectors target elements based on their attributes and values.
- Basic attribute matching:
input[type="text"] {
width: 300px;
}
- Substring matching:
a[href^="https://"] {
font-weight: bold;
}
a[href$=".pdf"] {
color: red;
}
img[src*="thumbnail"] {
border: 1px solid gray;
}
Understanding and effectively utilizing CSS selectors is key to efficient web design. By mastering these patterns, you can ensure your styles are applied as intended and create more dynamic, responsive, and interactive web pages.