Back to Explore
GuideVibeFix editorialUpdated Nov 20, 2026

Getting styles onto the right elements: CSS selectors, explained plainly

A selector is the first part of a rule: it decides who the styles land on. This guide follows MDN's Basic CSS selectors, Attribute selectors, and Pseudo-classes and pseudo-elements: type, class, ID, selector lists, universal, attribute selectors, pseudo-classes, pseudo-elements, chaining them together, plus a checklist for when a style does not show up.

Real photo: over-the-shoulder view of a man typing CSS code on a laptop, selectors visible on screen, with coffee, glasses, and a phone on the desk

Let me set the boundaries first. This site already has several front-end basics guides: DOM querying and traversal covered how to find elements in JavaScript with selectors, CSS Grid covered two-dimensional layout, and localStorage covered how data is stored. This guide covers none of those. It covers one thing: CSS selectors — the "naming" text at the front of a CSS rule that decides which elements on the page the rule lands on. The "Greenstone Cafe" below is the same fictional practice project as before: a small web tool that helps a street-corner cafe take orders. Earlier guides covered how its order page handles logic, splits modules, and draws Canvas pictures; this time we look at what the page looks like: how big the menu titles are, what color the daily-special card is, how sold-out dishes turn grey, and what happens when you hover over a dish. Every operation, code sample, and number that uses the cafe as an example was made up to explain how things work; none of it is a real record. Everything about selector syntax and behavior comes from three official MDN documents — "Basic CSS selectors", "Attribute selectors", and "Pseudo-classes and pseudo-elements" — listed in each article's meta information and evidence record. The examples from the documents, such as highlighting span and em, the notebox warning box, the four list items in the li[class] demo, and the first paragraph inside an article, are the documents' own examples, not a real service. This guide does not cover the child, adjacent-sibling, and general-sibling combinators, nor the functional pseudo-classes :is(), :where(), :not(), and :has(), nor the full specificity algorithm. It covers the set beginners use every day: type, class, ID, selector lists, universal, attribute, pseudo-class, and pseudo-element selectors, plus how to chain them together. When you finish, you should be able to do four things: name elements, filter elements by attribute, change styles by state, and know to check the selector first when a style does not show up.

Step 1: The selector is the first part of the rule — first work out who it names

MDN's "Basic CSS selectors" opens with the definition: a selector is the first part of a CSS rule, a pattern that tells the browser which HTML elements should have the property values inside the rule applied to them. The element or elements selected by the selector are called the subject of the selector. Think of a rule as a roll-call sheet: the selector is the name at the top, and the declaration block is the notice handed to those people. If you call the wrong name, it does not matter how well the notice is written — the style lands on someone else, or on nobody at all. Selectors are not only used in CSS; the same syntax finds DOM nodes in JavaScript, so what you learn here works inside querySelector too, as covered in the DOM guide. The cafe order page's stylesheet starts with naming: menu titles, dish names, prices, the daily special, the sold-out marks — each thing gets a way to be named before anyone talks about what it looks like. The most common beginner failure is not a wrong color value but a wrong name: you meant to change the daily-special card and changed every card on the site instead; you meant to turn one paragraph red and turned every paragraph on the page red. Every step below is one way of naming things, and the more precise the naming, the better the styles behave. Remember the order: first decide who you want to select, then write the selector, and only then write the declarations. Do it backwards — write a pile of pretty declarations first and then hunt for a selector to fit — and you will usually end up with a selector so long and tangled that you cannot read it yourself afterwards.

Step 2: Type selectors — write the tag name and you have named it

The most direct way to name something is to write the tag name. This is called a type selector, sometimes a tag name selector or element selector. MDN's example is plain: write span and you select every span in the document; write strong and you select every strong; write em and you select every em. In the document's demo, spans get a yellow background while strong and em turn rebeccapurple, and one rule changes every matching tag in the whole document at once. On the cafe order page, every dish name is an h3, every price is a span, and every description is a p: one h3 rule resizes every dish name on the page, and one p rule changes the line height of every description. The advantage of type selectors is that they save effort, and the disadvantage is exactly the same thing: they do not discriminate, and one rule hits every tag of that name on the page. Besides the dish descriptions, the order page has an "About us" page where the owner wrote a paragraph of text; you only wanted to change the line height of the dish descriptions, but the owner's words get changed too. That is the boundary of type selectors: they are right for setting the site-wide base — the default font of every paragraph, the default color of every heading — and wrong for changing one specific place by name. To narrow the scope, move on to class selectors. One more thing that is easy to miss: a type selector is just the tag name itself, with no extra symbol. Write h1 and you select h1; mistype one letter, writing h11, and the browser finds no such tag, so the rule quietly does nothing — no error, just a page that stares back at you.

Step 3: Class selectors — a dot in front, and mind the case

Class selectors are the naming method beginners use most every day. MDN puts it this way: the case-sensitive class selector starts with a dot character and selects everything in the document with that class applied to it. In the document's example, a class called highlight is applied in several places — on an h1, a span, and a p — and one .highlight rule turns all of their backgrounds yellow. "Case-sensitive" deserves its own sentence: .Highlight and .highlight are two different classes as far as the browser is concerned. If the HTML says class="Highlight" and the CSS says .highlight, the style simply does not attach, and there is no error message at all — it just silently fails. On the cafe order page, the daily-special card carries class="today" and sold-out dishes carry class="soldout", so .today changes only the special and .soldout changes only the sold-out dishes, without interfering with each other. Class selectors can be narrowed further: put the type selector directly in front of the class, with no whitespace between them, so span.highlight selects only spans with the highlight class and h1.highlight selects only h1s with that class. The two rules can give the same class different styles on different tags — in the document's demo, highlight on a span gets a yellow background and highlight on an h1 gets a pink one. You can also chain classes together: .notebox is a grey box, .notebox.warning is an orange border in bold, and .notebox.danger is a red border in bold, with no spaces in between, meaning the element must carry both classes at once. The document deliberately includes a div that carries only danger and not notebox, and it gets no styling at all, because the rule requires both classes to be present. This works well on the order page: a dish card is .dish, today's special is .dish.today, and a sold-out dish is .dish.soldout — .dish sets the base, and .dish.today and .dish.soldout each add their own mark, so the stylesheet neither repeats itself nor fights itself. An element can carry several classes, separated by spaces in the class attribute, and that is exactly what makes this pattern work.

Step 4: ID selectors — once per page, and do not use them as classes

An ID selector looks much like a class selector, except the dot becomes a hash: #one or #heading selects the element whose id has that value. MDN is explicit: an ID can be used only once per page, and an element can only have a single id value. In the document's example, p id="one" pairs with a #one rule that turns its background yellow, and h1 id="heading" pairs with an h1#heading rule that turns it rebeccapurple. Just like class selectors, you can put a type selector in front of the ID, meaning the rule only matches when both the element and the ID match. The trap in ID selectors is in those words "only once". The top navigation bar, the order button, and the big daily-special card on the order page each exist once, so naming them by ID fits well: #orderButton and #todayCard make it obvious you mean the one-of-a-kind thing on the page. But there are twenty dish cards, and giving every one of them id="dish" is wrong. MDN gives an explicit warning: using the same ID multiple times in a document may appear to work for styling purposes, but it is invalid code and will cause strange behavior in many places. JavaScript's getElementById returns only the first match, anchor jumps only recognize the first one, and while the styles look right, the scripts and the jumps are all broken. Worse, an ID outweighs a class by a lot, so once you have written #todayCard, overriding it later with a class becomes very painful, and beginners often fall into a loop of "I wrote the style, why does nothing change?" The rule is: use an ID only for something that truly exists once, and use classes for anything that can repeat. On the cafe order page, only a handful of things deserve an ID — the top bar, the order button, the cart drawer — and everything else is a class.

Step 5: Selector lists — a comma means "or", and one bad entry kills the whole rule

When several different selectors need to share the same declarations, do not copy the same declarations three times. Join the selectors with commas into one selector list. MDN's example is h1 and .special both turning blue: instead of two rules, write h1, .special as one. Whitespace before or after the comma is fine, and putting each selector on its own line is fine too — it is often more readable. On the order page, dish names (h3) and the recommendation tagline (.tagline) both want the same dark-brown heading color, so h3, .tagline does it in one place; when the color needs to change later, there is only one place to edit. The thing to really remember here is not the comma itself but the warning MDN gives right after: when selectors are grouped this way, if any selector is syntactically invalid, the whole rule will be ignored. The document's example is clean: h1 on its own is fine, and ..special (two dots — an invalid class selector) on its own is fine too, since it simply matches nothing; but write h1, ..special and even the h1 loses its blue, because the entire rule is treated as invalid and thrown away. In other words, a comma list is all-or-nothing. This is where beginners trip most often: they copy a selector list from the web, one entry in it uses a new syntax their browser does not support yet, or a finger slips and adds an extra dot, and the whole rule quietly stops working while the page shows no change — and they assume the color value must be wrong. The way to debug it is simple: split the list apart and test each selector on its own, find which one is broken, and then decide whether to fix it or move it into a separate rule. A matching habit helps: put each selector in the list on its own line, so the broken line is visible at a glance instead of hiding in a crowded row.

Step 6: The universal selector — one asterisk selects everything, so save it for resets

The universal selector is a single asterisk, written *, and it selects everything in the document. MDN's example uses it to remove the margins on all elements: * { margin: 0; }, which in one line clears the spacing browsers give headings and paragraphs by default, and the page immediately becomes more compact. This kind of "clear everything" rule shows up often in reset stylesheets, but MDN also warns that the universal selector makes global changes, so it should be used for very specific situations, such as the one just described. The order page's stylesheet opens with * { box-sizing: border-box; }, meaning every element measures its width and height by the border box — a one-time ground rule that never needs touching again. The universal selector can also be combined with other selectors: p * selects all the nested elements inside a p element, and article :first-child means the same thing as article *:first-child — any element that is the first child of an article. MDN spends a paragraph on the difference between two lookalikes: article :first-child is easily misread as "select an article element that is the first child", while article:first-child (with no space in the middle) is what actually means that. Writing it as article *:first-child makes the meaning obvious at a glance: there is an "any element" sitting in front of the colon, and although both forms select exactly the same things, the second one is harder to misread. MDN is honest that this technique is rarely seen in published websites — MDN itself does not use it much — but if you find it easier to read, you are welcome to use it in your own code. The rule for the universal selector is one line: it is carpet bombing, not a scalpel. Use it to set global ground rules; use it to style one specific place and sooner or later it will hit something you did not mean to touch.

Step 7: Attribute selectors, part one — whether the attribute exists, and whether the value is exactly this

The selectors so far name things by tag name, class name, or ID. Attribute selectors take a different approach: they name elements by the attributes they carry. MDN defines them as selectors that enable the selection of an element based on the presence of an attribute alone, or on various matches against the value of the attribute. The first group has four forms. Writing [attr] means the attribute only has to be there — a[title] selects every link with a title attribute, whatever the title says. Writing [attr=value] means the attribute's value must be exactly the given string — a[href="https://example.com"] selects only the link whose address is exactly that URL. Writing [attr~=value] means the value is exactly this, or the value is a space-separated list of values and one of them is this — as in p[class~="special"]. Writing [attr|=value] means the value is exactly this, or begins with this value immediately followed by a hyphen — div[lang|="zh"] matches lang="zh" and also lang="zh-Hant", because the latter begins with zh-. MDN's example with four list items makes this very clear: li[class] matches every li with a class attribute, which is all except the first one; li[class="a"] matches only the item whose class is exactly a, and the item with class="a b" does not count because its value is not precisely a; li[class~="a"] matches the second and third items, because the third item's value a b is a whitespace-separated list that contains a. On the order page this group is immediately useful: input[type="text"] selects only text inputs and leaves the submit button alone; a[href] underlines every piece of text that actually links somewhere; [data-soldout] selects every element carrying a sold-out marker, whatever the marker's value is. Remember the temperament of exact matching: [class="a"] judges the whole value, so several classes joined together do not count as equal — when you want "this value is in the list", use ~= instead.

Step 8: Attribute selectors, part two — start, end, and anywhere in between

Beyond exact matching, attribute selectors offer three substring-matching forms for the case where you want "part of the value". MDN's table is clear: [attr^=value] matches elements whose attribute value begins with the given value, as in li[class^="box-"]; [attr$=value] matches elements whose attribute value ends with the given value, as in li[class$="-box"]; [attr*=value] matches elements whose attribute value contains the given value anywhere within the string, as in li[class*="box"]. The document's example is the classes box-warning and box-error: to select both at once, you do not need to write out both class names — [class^="box-"] does it, because they both start with box-. A second example with four list items pins down the difference between the three forms: li[class^="a"] matches values starting with a, which is the first two items; li[class$="a"] matches values ending with a, which is the first and third items; li[class*="a"] matches values where a appears anywhere, which is all four items. On the order page, dish card classes follow a naming pattern: .dish-hot is a hot drink, .dish-cold is a cold drink, and .dish-new is a new item, so [class^="dish-"] selects every dish card at once, [class$="-new"] selects only new items, and [class*="hot"] selects everything with hot in its name. The easiest mistake with substring matching is losing control of the range: [class*="new"] selects not only .dish-new but also .news-banner and .renew-card, because any value containing the three letters new matches. Before writing one, decide what you actually want: the start, the end, or anywhere in the middle? Use ^= for the start, $= for the end, and *= for anywhere in the middle, and if exact matching will do, do not reach for substrings. One more detail: put the attribute value in quotes, as in [href="https://example.com"] — MDN's examples always carry quotes, and keeping that habit avoids a lot of mysterious failures.

Step 9: Pseudo-classes — they only match while the element is in a certain state

Pseudo-classes are the liveliest kind of selector. MDN defines them as selectors that select elements that are in a specific state — for example, they are the first element of their type, or they are being hovered over by the mouse pointer. They tend to act as if you had applied a class to some part of your document, often helping you cut down on excess classes in your markup and giving you more flexible, maintainable code. A pseudo-class is a keyword that starts with a single colon — :hover is a pseudo-class. The document's classic example is the first paragraph inside an article: you could add class="first" to that paragraph and write a .first rule to make it larger and bold. But that is annoying to maintain — if someone adds a new paragraph at the top of the document, the class has to move to the new first paragraph. Using the :first-child pseudo-class selector instead always targets the first child element of an element (the article in this case), and the HTML never needs editing again — which matters when the HTML is generated by a CMS and you cannot edit it anyway. The document also notes that it is valid to write a pseudo-class with no element selector before it: writing :first-child on its own is equivalent to *:first-child and applies to any element that is the first child of an article, not just a paragraph — though usually you want more control than that, so you add something more specific. Another group of pseudo-classes only applies when the user interacts with the document, sometimes called dynamic pseudo-classes: :hover only applies if the user moves their pointer over an element, typically a link, and :focus only applies if the user focuses the element by clicking or using keyboard controls. MDN's example sets a:link and a:visited to rebeccapurple and bold first, then a:hover to hotpink, so the color changes the moment the mouse moves over the link. On the order page, .dish:hover lifts a dish card slightly, and :first-child alone can pick out the first item in the "today's special" list. The principle for pseudo-classes is simple: a state is temporary, so the style should be temporary too. Hover, focus, and selection are states, not an element's identity — do not use a pseudo-class to do a class selector's job.

Step 10: Pseudo-elements — as if a brand-new element had been added to the document

Pseudo-elements look much like pseudo-classes, but they mean something completely different. MDN puts it this way: pseudo-elements behave in a similar way, but they act as if you had added a whole new HTML element into the markup, rather than applying a class to existing elements. A pseudo-element starts with a double colon — ::before is an example of a pseudo-element. The document's example is ::first-line: if you wanted to select the first line of a paragraph, you could wrap it in a span and use an element selector, but that would fail if the words you wrapped were longer or shorter than the parent element's width. Since we tend not to know how many words will fit on a line — that changes if the screen width or font size changes — it is impossible to robustly do this by adding HTML. The ::first-line pseudo-element selector does it for you reliably: if the number of words increases or decreases, it still only selects the first line. It acts as if a span had been magically wrapped around that first formatted line, and updated each time the line length changed. Then there is the pair ::before and ::after, used together with the content property to insert content into your document using CSS — a technique called generated content. In the document's example, .box::before pairs with content: "This should show before the other content. " plus a yellow background, so the inserted text is easy to tell apart from the paragraph's own content. Change ::before to ::after and the text is inserted at the end of the element instead of the beginning. The document warns at the same time that inserting strings of text from CSS is not really something we do very often, because that text is inaccessible to some screen readers and might be hard for someone to find and edit in the future. A more valid use of these pseudo-elements is to insert an icon — for example the little arrow added after a link, a visual indicator that you would not want read out by a screen reader. Generated content is also frequently used to insert an empty string, which can then be styled just like any element on the page: in the document's next example, .box::before gets content: "", display: block, a width and height of 100px, a rebeccapurple background, and a 1px solid black border, and a purple square appears on the page. Some early pseudo-elements used the single-colon syntax, so you may sometimes see that in code; modern browsers support the early pseudo-elements with single- or double-colon syntax for backwards compatibility, but new code should always use the double colon, so a reader can tell at a glance that this is a pseudo-element and not a pseudo-class.

Step 11: Chain them together — and note that a space changes the meaning entirely

The forms from the previous steps are not meant to be used alone; they can be chained into a single selector, each part handling one piece of the meaning. MDN's example is article p:first-child::first-line: article is the ancestor, p is the type, :first-child is the state, and ::first-line is the pseudo-element, adding up to "the first line of the first p inside an article". It reads like a sentence, ordered from outside to inside — from identity to state to a part of the element. The easiest mistake in chained selectors is the space: a space is itself a selector, the descendant combinator, and having one or not having one changes the meaning completely. Step 6 already covered the article :first-child versus article:first-child distinction: the first means the first child inside an article, while the second means an article element that is itself the first child of something else. The same logic applies everywhere: .dish .today is a today element inside a dish, while .dish.today is one single element carrying both the dish and today classes; one extra space typed by a slipping finger, and the style lands somewhere else entirely — without any error. The way to check a chained selector is to read it piece by piece: start with the rightmost part, which is the element actually selected, and then read leftwards, with each part adding a condition. In article p:first-child::first-line, the subject is ::first-line, and the conditions are p, first child, and inside an article. Read this way, the wrong part shows itself at once. A matching habit: do not let a chain grow too long. Once it passes three or four parts, stop and ask whether the element should simply get a class of its own so it can be named directly. A selector's job is naming, not prose — the shorter and more precise the name, the easier it is to maintain.

Step 12: When a style fails, check the selector before the declarations

When a style does not show up, a beginner's first instinct is often to change the color value, change the font size, or add !important. In fact, most of the time the selector named the wrong element. The chart below shows a fictional count of CSS selector mistakes on the Greenstone Cafe order page over one month: 132 in total. Misspelled class names or wrong case lead with 28 (21.2%); using IDs everywhere and repeating them on one page follows with 24 (18.2%); a missing space in a descendant selector, so the rule selected the element itself, with 22 (16.7%); :hover written in the wrong place so nothing happens on hover with 18 (13.6%); wrong equals signs or quotes in attribute selectors with 16 (12.1%); mixing up single and double colons on pseudo-elements with 14 (10.6%); and one bad entry in a selector list voiding the whole rule with 10 (7.6%). 28 + 24 + 22 + 18 + 16 + 14 + 10 equals 132, and the percentages add up to 100.0%, so the books balance. The top three mistakes are all about naming the wrong thing, and the last four are all about getting a symbol wrong — the declarations themselves are rarely the problem.

Bar chart: fictional breakdown of 132 CSS selector mistakes in one month on the Greenstone Cafe order page, with misspelled class names at 28 the largest group

Here is a checklist to run through, in order, when a style does not appear. First, open the browser developer tools and see whether the rule shows up on the element at all: if the rule is not there, the selector did not match it, so read the selector piece by piece from right to left and find which condition is wrong; if the rule is there but crossed out, that is a weight or ordering problem, not a failure to match. Second, check class and ID names letter by letter, including case — whatever the HTML says, the CSS must say the same, and one letter off is enough to break it. Third, search the whole page for repeated IDs, and turn any duplicate into a class. Fourth, split a selector list apart and test each entry alone, so one broken selector cannot take down the whole rule. Fifth, fix the quotes and equals signs in attribute selectors, and confirm whether a substring match should test the start, the end, or the middle. Sixth, confirm that pseudo-classes such as :hover and :focus are written on the element that is supposed to change, not on its parent. Seventh, confirm that pseudo-elements use a double colon, and that ::before and ::after have a content property — without content they will not display. Eighth, check the spaces in chained selectors: no space when you mean the same element, one space when you mean something inside it. Ninth, use the universal selector and very long selector chains sparingly — the shorter the name, the easier it is to maintain. Tenth, test by hand in the browser after every change: hover over it, focus it, and resize the window to see whether the first line changes. Selectors, in the end, are about naming: name things precisely and the styles behave; name them wrong and even the prettiest declarations are wasted.

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles

Real photo: hands typing on a MacBook Pro showing JavaScript code that changes HTML content, with a white mouse, papers, and binders on a white desk
Guide
Functions without the confusion: JavaScript functions, parameters, and arrow functions, explained plainly

You already call functions every day; this guide names what you have been doing. Following MDN's Functions, Arrow function expressions, and Rest parameters: declarations versus expressions, parameters and arguments, default values, rest parameters, spread syntax, return values, arrow function shorthand, the this trap, callbacks, and scope.

Tool TipsFrontend EngineeringAI Coding
Real photo: a Casio scientific calculator on a wooden desk showing 123456789 + 987654321 = 1111111110, beside handwritten math notebooks, a pen, a mug, and a laptop edge
Guide
Don't let 0.1 + 0.2 break your bill: JavaScript numbers and Math, explained plainly

Numbers in JavaScript are one type, Number, stored as 64-bit floats — which is why 0.1 + 0.2 is 0.30000000000000004. This guide follows MDN's Basic math in JavaScript, Math, and Number: one number type, float error, counting money in cents, converting strings, NaN and Infinity, safe integers, the four rounding methods, Math.random, the Math toolbox, and formatting for display.

Tool TipsFrontend EngineeringAI Coding
Real photo: a hand holding a stylus draws a colorful picture on a tablet, with a paint palette and brushes on the desk
Guide
Drawing without images: Canvas basics, explained plainly

No image files, no library: the order page's weekly bar chart and smiley face are drawn live with Canvas. This guide follows MDN's Canvas tutorial — Basic usage, Drawing shapes, and Applying styles and colors: the 300×150 default, the top-left origin, fillRect and strokeRect, the beginPath-moveTo-lineTo-fill/stroke path pattern, arcs in radians, Bezier curves, fillStyle and strokeStyle, transparency, line styles, gradients, patterns, shadows, and redrawing for motion.

Tool TipsFrontend EngineeringAI Coding