One fundamental aspect of CSS is selecting elements within an HTML document to apply styles. This is achieved through CSS selectors.
The most straightforward selector targets elements based on their type.
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;
}
Selects all elements on a page.
* {
margin: 0;
padding: 0;
}
Combine selectors to apply the same style to multiple elements.
h1, h2, h3 {
font-family: 'Arial', sans-serif;
}
Select elements that are descendants of another element.
article p {
color: purple;
}
Use combinators to refine selections.
div > p {
font-style: italic;
}
Targets elements based on their attributes.
input[type="text"] {
border: 1px solid #ccc;
}
Select elements with a specific attribute, regardless of the value, or based on a substring.
input[required] {
border: 2px solid red;
}
a[href*="example"] {
color: orange;
}
Apply styles based on the state of an element.
a:hover {
color: red;
}
Target specific parts of an element.
p::first-line {
font-weight: bold;
}
Exclude elements from the selection.
p:not(.special) {
font-style: normal;
}
Select elements based on their position within a parent or of a specific type.
ul li:nth-child(odd) {
background-color: #f2f2f2;
}
div p:nth-of-type(2) {
font-weight: bold;
}
Select the first, last, or only child elements of a parent.
ul li:first-child {
font-weight: bold;
}
p:only-child {
color: green;
}
Style elements in focus or checked state.
input:focus {
border: 2px solid blue;
}
input[type="checkbox"]:checked {
background-color: #ffd700; /* yellow */
}
By understanding these selectors, you possess the tools to precisely style elements and create visually appealing and responsive web designs. As you continue your CSS journey, remember to experiment and combine these techniques for optimal results. Happy Coding! ❤️