CSS Selectors - Learn Web Development MDN
CSS Selectors - Learn Web Development MDN
CSS selectors
What is a selector?
A CSS selector is the first part of a CSS
Rule. It is a pattern of elements and other
terms that tell the browser which HTML
elements should be selected to have the
CSS property values inside the rule applied
to them. The element or elements which are
selected by the selector are referred to as
the subject of the selector.
Selector lists
If you have more than one thing which uses
the same CSS then the individual selectors
can be combined into a selector list so that
the rule is applied to all of the individual
selectors. For example, if I have the same
CSS for an h1 and also a class of
.special , I could write this as two separate
rules.
CSS
h1 {
color: blue;
}
.special {
color: blue;
}
CSS
h1, .special {
color: blue;
}
CSS
h1,
.special {
color: blue;
}
Type selectors
Veggies es bonus vobis,
proinde vos postulo essum
magis kohlrabi welsh onion
daikon amaranth tatsoi
tomatillo melon azuki bean
garlic.
Interactive editor
span {
background-color: yellow;
}
strong {
color: rebeccapurple;
}
em {
color: rebeccapurple;
}
<h1>Type selectors</h1>
<p>Veggies es bonus vobis,
proinde vos postulo essum magis
<span>kohlrabi welsh
CSS
h1 {
color: blue;
}
..special {
color: blue;
}
CSS
h1, ..special {
color: blue;
}
Types of selectors
There are a few different groupings of
selectors, and knowing which type of
selector you might need will help you to
find the right tool for the job. In this article's
subarticles we will look at the different
groups of selectors in more detail.
CSS
h1 {
}
CSS
.box {
}
CSS
#unique {
}
Attribute selectors
This group of selectors gives you different
ways to select elements based on the
presence of a certain attribute on an
element:
CSS
a[title] {
}
CSS
a[href="https://example.com"]
{
}
CSS
a:hover {
}
CSS
p::first-line {
}
Combinators
The final group of selectors combine other
selectors in order to target elements within
our documents. The following, for example,
selects paragraphs that are direct children
of <article> elements using the child
combinator ( > ):
CSS
article > p {
}
Summary
In this article we've introduced CSS
selectors, which enable you to target
particular HTML elements. Next, we'll take a
closer look at type, class, and ID selectors.
MDN Support
Careers
Advertise with us
Hacks Blog