How to target part of a webpage using CSS selectors


Cascading Style Sheets (CSS) allow you to transform the look of your web pages. From fonts and colors to spacing and general layout, all kinds of design tools are right at your fingertips. While CSS is a complicated language in its entirety, there are only two basic concepts you need to understand to get started.

It all starts with identifying exactly what part of a page you want to style.

CSS = Selectors + Declarations

A CSS file contains a series of rules describing how an HTML file should be formatted. Each rule consists of two parts: what to style and how to style it. The first part is controlled using a series of terms called “selectors”.

An example of a CSS rule

The examples in this article include style declarations, but they are not the focus: the selectors themselves are.

Historically, there were three levels (or versions) of CSS selector with varying degrees of browser support. In 2020, according to Can I use, they are all available to over 99% of users worldwide.

Level 1 selectors

Level 1 introduced the four basic types of selectors which cover a large number of cases even today.

Model Matches
E all elements E
.c all elements with class = “c”
#myid the element with id = “myid”
E F an F element inside an E element
Pseudo-classes
E:link a hyperlink to a page that has not yet been visited
E:visited a hypertext link to a page already visited
E:active a currently selected hyperlink
Pseudo-elements
E::first-line the first formatted line of an E element
E::first-letter the first formatted letter of an E element

Type selector

The simplest selector is the “type selector”. It targets all instances of an element, such as a paragraph or bold text:

p { margin-bottom: 0; }
b { font-family: sans-serif; }

Class selector

The class attribute is used to add additional semantics to an HTML element, such as a specific paragraph type. These elements can be selected in CSS as follows:

.intro { font-weight: bold; }

This selector would correspond to:

…

But note that it would also match:

    …

If you want it to apply only to the introductory paragraphs, you can combine the type selector and the class selector:

p.intro { font-weight: bold; }

Identity selector

The HTML id attribute must be unique within a document, for example if you have:

…

This should be the only item with a “content” identifier. An ID picker allows you to target that specific element in a document:

#contents { color: #333; }

Descendant selector

Strictly, a “combiner” because this selector is all about the space between two others. HTML is hierarchical, as explained in our DOM overview. A descendant selector is used to identify an element by its context within another element:

table b { font-weight: normal; }

Pseudo classes and elements

Pseudo-selectors target classes or elements that do not explicitly exist but are still made available. Think of them as special content bonuses:

p::first-line { text-transform: uppercase; }

Selection lists

Use a comma to combine selectors in a list if you want to apply the same set of rules to each. In the place of:

th { padding: 1em; }
td { padding: 1em; }

You can write:

th, td { padding: 1em; }

Specificity

A stylesheet is a series of rules that use a selector to match an element, but what happens when multiple rules match a given element? The resulting behavior is governed by “specificity” which defines which rule is used in a case such as:

p.intro { color: black; }
p { color: gray; }

In such cases, the overriding rule is defined by its specificity, as follows:

  1. ID selectors (`# contents`) are the most specific.

  2. Class selectors (`.author`) are less specific.

  3. Type selectors (`p`) are the least specific.

When calculating specificity, each level is only taken into account if two selectors have the same score at the top level, so “#contents” is more specific than “article.news p.author.special” because the first “ wins ”on ID selectors.

Level 2 selectors

The next revision of CSS selectors introduced attribute selectors, extended pseudo-classes and pseudo-elements, and added two new combiners.

Model Matches
* any element
E > F an element F child of an element E
E + F an F element immediately preceded by an E element
Attribute selectors
E[foo] an E element with a “foo” attribute
E[foo="bar"] an E element whose “foo” attribute is exactly “bar”
E[foo~="bar"] an E element whose attribute “foo” is a list of values ​​separated by spaces, one of which is “bar”
E[foo|="en"] an E element whose attribute “foo” has a list of values ​​separated by hyphens starting with “en”
Pseudo-classes
E:first-child an element E, first child of its parent
E:lang(fr) an element of type E in “fr” language
Pseudo-elements
E::before content generated before the content of an E element
E::after content generated after the content of an E element

Universal selector

The “*” matches any item. This isn’t often very useful, but if you want to reset some default margins, for example, you can do that:

* { margin: 0; }

Attribute selectors

Attribute selectors allow you to very precisely target styles, filtered by the attribute of an element:

aHow to Target Part of a Web Page Using CSS Selectors { text-decoration: underline dotted; }

Child combinator: one element immediately inside another

Similar to the Descendant Combiner, but this only matches immediate children, not descendants further down the tree. For example, “ul> li” will only match the text “Section 1” here, not “Section 1.1”:



  • Section 1

    • Section 1.1

    • Section 1.2




Adjacent Sibling Combiner: The Next Sibling

h1 + p { font-weight: bold; }

Often useful for controlling margins, or an introductory paragraph without a specific class, this selector only matches an element if it immediately follows another. In the example, only the first paragraph here will be matched, not the second:

Contents


some extra text

Introductory paragraph


Following paragraph


Note that this selector only considers elements, not text, when deciding which sibling is next.

Heritage

Some CSS properties inherit their value from an ancestor element. In practice, this means, for example, that defining the font of the “body” element means that every paragraph, table, etc. also uses this same font.

Of course, this is exactly what you would expect, but consider a property that does not inherit: “margin”, for example. You wouldn’t want every bold paragraph or piece of text to have the same margin as the entire document.

Related: Simple CSS Code Examples You Can Learn In 10 Minutes

A good rule of thumb is to target items as generally as it makes sense – don’t target each item individually when a simple “body” selector will suffice.

Level 3 selectors

Many other pseudo-classes have been added at this level, as well as attribute selectors and a new combiner.

Model Matches
E ~ F an F element preceded by an E element
Attribute selectors
E[foo^="bar"] an E element whose attribute “foo” begins with the string “bar”
E[foo$="bar"] an E element whose attribute “foo” ends with the string “bar”
E[foo*="bar"] an E element whose attribute “foo” contains the substring “bar”
Pseudo-classes
E:root an E element, root of the document
E:nth-child(n) an element E, the n-th child of its parent
E:nth-last-child(n) an element E, the n-th child of its parent, from the last
E:nth-of-type(n) an element E, the n-th sibling of its type
E:nth-last-of-type(n) an element E, the n-th sibling of its type, counting from the last
E:last-child an element E, last child of its parent
E:first-of-type an element E, first sibling of its type
E:last-of-type an element E, last brother of its type
E:only-child an E element, the only child of its parent
E:only-of-type an element E, only sibling of its type
E:empty an E element that has no children (including text nodes)
E:target an element E being the target of the referral URI
E:enabled a user interface element E that is enabled
E:disabled a user interface element E that is disabled
E:checked a user interface element E that is checked
E:not(s) an element E which does not correspond to the simple selector s

Attribute selectors

You can select items with an attribute that starts with a given value: a[href^="https:"], ends with a given value: img[src$=".gif"], or contains a value: a[*="value"].

Pseudo course

Additional pseudo-classes include “: last-child”, “: empty” (to match an element with no content) and “: checked” which matches an element as a checkbox entry, but only when it is. checked.

General sibling combinator: a next sibling

Similar to the adjacent sibling combiner in level 2, this matches any sibling that comes after another, not just the next one:

h1 ~ p { font-size: 110%; }

CSS selectors and how to use them

Now you know pretty much everything there is to know about how to select part of a webpage using CSS. You are now ready to style your pages with the wide variety of CSS properties that cover everything from colors to layout.

Image Credit: Pankaj Patel /Unsplash


Screenshot of examples of CSS properties used in a code snippet

The CSS3 essential properties cheat sheet

Master essential CSS syntax with our CSS3 properties cheat sheet.

Read more


About the Author


Comments are closed.