designwithfocus

CSS

How to CSS Select Elements with Selectors

By Design With Focus Team 7 min read
A CSS selector next to the HTML element it matches

Short answer

To select an element in CSS, write a selector for a type, class, ID, or attribute, then load that rule in a stylesheet. A combinator reaches a child or a sibling. A pseudo-class matches a state such as hover. A pseudo-element, written with two colons, styles a piece of the render tree that is not its own HTML element.

Last verified against the sources listed below.

Key takeaways

  • MDN says a class selector is a period plus the class name, and an ID selector is a hash plus the id.
  • A space selects descendants. A greater-than sign selects only direct children.
  • The plus sign selects the next sibling. A tilde selects later siblings with the same parent.
  • MDN says pseudo-elements use a double colon and are not nodes in the document tree.
  • MDN names three ways to apply CSS: an external file, a style element, and a style attribute.
  • An animation needs animation-name and animation-duration, plus a matching @keyframes rule.

How to CSS select an element is to name it with a selector and put that selector in a stylesheet the page actually loads. The selector is the part before the curly braces. The declarations inside only run if the selector matches.

CSS is the language those rules are written in. This guide is the matching step: type, class, ID, combinators, states, and pseudo-elements.

Layout that happens after a match, such as margin and padding, is the box model.

What you need

You need an HTML element with a tag name and, if you want a class or ID selector, a class or id attribute. You need a stylesheet the document loads. MDN’s getting started guide names three ways: an external .css file, a style element in the head, and a style attribute on one element.

A generated control is a fine thing to practice on. A CSS button generator writes a button rule. You still have to select that button yourself if you change it later.

Select the element

  1. Add a class to the element you care about, for example class="buy".
  2. Write a class selector with a leading period: .buy. MDN says .index matches class="index".
  3. Or write a type selector, such as button, or an ID selector such as #toc for id="toc".
  4. Put declarations in the block, then save the sheet.
  5. Link an external sheet from the head with rel="stylesheet" and the file in href, which is the pattern MDN shows.
  6. Reload the page and check that the element changed. If it did not, use the table at the end.

MDN’s selector guide says there should be only one element with a given id. If several share it, the ID selector matches all of them. Do not treat # as “first one only.”

Combinators

A combinator joins two selectors and limits where the second may sit.

MDN defines four you will use constantly:

  • A descendant combinator is one or more spaces. div span matches every span inside a div.
  • A child combinator is >. div > span matches only spans that are direct children of a div.
  • A subsequent-sibling combinator is ~. h2 ~ p matches every p that follows an h2 under the same parent, immediately or not.
  • A next-sibling combinator is +. h2 + p matches only the p immediately after an h2, with the same parent.

Selectors Level 4 is the W3C specification those selector types belong to, including the pseudo-element section. Use the MDN pages above when you want the short form of each symbol.

How to use pseudo elements in CSS

A pseudo-class matches a state of an element, such as :hover or :focus. It is written with one colon. The element is still a real node in the document.

A pseudo-element is different. MDN’s pseudo-element guide says these are abstract pieces of the render tree, not nodes in the document tree. They use a double colon. You attach one to a selector, as in p::first-line.

The page lists ::before and ::after among the pseudo-elements you can style, along with ::placeholder, ::selection, and ::first-line.

p::before does not find a tag named before. It styles a generated box associated with the paragraph. If you write a single colon where MDN shows two, you are using the old pseudo-element syntax or, worse, naming a pseudo-class that does not exist. Prefer the double colon MDN documents.

How to display CSS in HTML

How to display CSS in HTML means choosing one of the three attachments MDN describes.

An external stylesheet is a separate file. MDN’s example link is:

<link rel="stylesheet" href="styles.css" />

The rel attribute says the linked file is a stylesheet. The href is the path. One file can be linked from many pages.

An internal stylesheet is a style element in the head. MDN’s sample is a rule that sets paragraphs to purple. MDN says this can help when a CMS blocks external files, and that it is less efficient than an external file on a site with more than one page.

Inline styles are declarations on a single element. MDN’s sample is a span with style="color: purple; font-weight: bold;". Declarations in that attribute are separated by semicolons. MDN says to avoid this when you can, because the rules sit in the markup instead of a sheet you can reuse.

The HTML living standard says all HTML elements may have the style content attribute set, and that a document using it must still be understandable if those attributes are removed. The section is the style attribute.

How to make CSS animations

How to make CSS animations starts only after a selector matches the element. MDN’s animations guide says you set the animation property, or its pieces, for timing and duration. The frames themselves are an @keyframes rule.

The guide’s pattern is animation-duration: 3s and animation-name: slide-in, with a @keyframes slide-in rule that describes the look. The name on the element and the name on @keyframes have to be the same. You can list several names. MDN shows animation-name and animation-duration as comma-separated lists when one element runs more than one animation.

How to add CSS animation to a class you already wrote is the same pair of declarations inside that class block. Selecting .buy does not move it. Adding the name and the duration does, if the keyframes exist.

How to use CSS frameworks

How to use CSS frameworks is still “load a stylesheet, then select.” Bootstrap’s getting started page for version 5.3 says to include Bootstrap’s CSS with a link in the head. The CDN href on that page points at [email protected] in the minified CSS file. The JavaScript bundle is a separate script near the end of the body.

After that link, Bootstrap’s class names are ordinary class selectors in the file you just loaded. Add your own sheet after it when you need to override a class. The selector language does not change.

Symptom Likely cause What to change
Nothing changes The sheet is not linked, or the path in href is wrong Fix the link in the head and reload
The class rule misses The class token and the selector differ, including case Make .buy match class="buy" exactly
A nested span is not styled You used > but the span is not a direct child Switch to a descendant combinator, a space
The next paragraph is missed You used + and another node sits between the pair Use ~ if any later sibling should match
::before does nothing The name or the colon count is wrong Use the double-colon form MDN shows
The animation does not run animation-name does not match @keyframes Use one shared name, and set a duration

Select the smallest set of elements that should change. A type selector such as p is short, and it also matches every paragraph. A class is usually the selector you can live with after the markup grows.

Frequently asked questions

How to display CSS without a separate file?

MDN's getting-started guide names three ways to apply CSS: an external stylesheet, an internal stylesheet, and inline styles. Internal CSS goes in a style element in the head. Inline CSS goes in a style attribute on one element. MDN says an internal sheet is less efficient than an external file once the site has more than one page, and it says to avoid inline styles when you can. Use them when you cannot change the external file.

How to add CSS animation after the element is selected?

MDN's animations guide says the animation property, or its sub-properties, sets timing and duration. It does not draw the frames. The look comes from an @keyframes rule whose name matches animation-name. The guide's example sets animation-duration to 3s and animation-name to slide-in. If the names differ, the element is selected and nothing moves. Duration without keyframes has no frames to play.

Does a class selector match part of a class string?

MDN says a class selector matches elements whose class attribute contains that class name, written with a leading period. The example is .index for class="index". It is the class token, not a search through unrelated words. An ID selector matches the id attribute and is written with a hash. MDN also says an id should be unique, but if several elements share it, the ID selector matches all of them.

When should a child combinator replace a descendant combinator?

Use a child combinator when you want only the elements directly inside the parent. MDN says div greater-than span matches span elements that are direct children of a div, while div followed by a space and span matches span elements anywhere inside. The child form stays quiet when someone wraps the span in another tag. The descendant form starts matching that new wrapper. Pick the narrower one when the markup may grow.

How to use CSS frameworks without giving up selectors?

A framework is still a stylesheet. Bootstrap's version 5.3 getting-started page says to put the CSS link in the head. After that file loads, you select elements with the classes the framework defined, or with your own selectors in a sheet that loads later. You do not get a new selection language. If your rule never wins, the framework's selector may be more specific, or your file may be linked first.

Sources