CSS selectors are like a set of instructions used to find and style HTML elements on a web page. Imagine you have a group of boxes, each with different labels on them. If you want to paint all boxes with a certain label, you'd first identify those boxes using their labels. In CSS, these labels are akin to selectors.
When you write CSS code, you use selectors to tell the browser which HTML elements (like paragraphs, headings, or links) you want to apply styles to. For example:
- If you use the selector
p
, you're telling the browser to apply the style to all<p>
(paragraph) elements. - If you use a class selector like
.blue-text
, you're targeting all elements with the classblue-text
. - An ID selector like
#header
targets the element with the specific ID ofheader
.
In short, selectors are the part of CSS that help you choose which parts of your webpage to style. They're the first step in the process of making your website look the way you want it to.
Selects all elements of a specified type.
HTML Example:
<p>This is a paragraph.</p>
<h1>This is a heading.</h1>
CSS Example:
p {
color: blue;
}
h1 {
font-size: 20px;
}
Selects all elements with a specified class attribute.
HTML Example:
<div class="box">Box 1</div>
<div class="box">Box 2</div>
CSS Example:
.box {
border: 1px solid black;
}
Selects a single element with a specified id attribute.
HTML Example:
<div id="unique-element">Unique Element</div>
CSS Example:
#unique-element {
background-color: yellow;
}
Selects all elements that are descendants of a specified element.
HTML Example:
<div>
<p>Paragraph inside a div.</p>
</div>
<p>Paragraph outside a div.</p>
CSS Example:
div p {
color: green;
}
Selects all elements that are the direct children of a specified element.
HTML Example:
<ul>
<li>List Item 1</li>
<li>List Item 2</li>
</ul>
CSS Example:
ul > li {
font-weight: bold;
}
Selects an element that is directly after another specific element.
HTML Example:
<div>First div</div>
<p>Adjacent paragraph to the first div.</p>
<p>Another paragraph.</p>
CSS Example:
div + p {
color: red;
}
Selects elements based on the presence or value of a given attribute.
HTML Example:
<input type="text" /> <input type="checkbox" />
CSS Example:
input[type="text"] {
background-color: lightgrey;
}
Selects elements based on their state or relation to other elements.
HTML Example:
<a href="https://example.com">Link</a> <input type="checkbox" checked />
CSS Example:
a:hover {
color: red;
}
input:checked {
outline: 2px solid blue;
}