JavaScript Refresher and Detailed Study - Part 14 (Includes CSS Basics Quick Refresher and Study)
Contents
- Gemini chat and dates
- Use Element classList prop (iterable, with add/remove/toggle methods) for 99% of work; use Element className prop to overwrite entire string; Element attributes prop or getAttribute('class') can be ignored
- Global in HTML "Global attributes" is diff from JS globals; Terminology varies across MDN technology sections: HTML - WHATWG, Web API - Web IDL (WHATWG/W3C), JavaScript - ECMAScript, CSS - W3C
- Objects used to represent attributes; Only
nameandvalueproperties ofAttrJavaScript class are relevant, rest is legacy baggage and can be ignored; Browser lazy-allocation trick forAttr - NamedNodeMap (Element attributes object type) is not a JavaScript Map object but a WebIDL interface/term; In modern JavaScript apps,
elem.attributes.<attrName>is practically never used for any attribute, standard or custom - Manipulation of attributes (usually via their DOM properties) is vital part of UI of modern JS apps
- In Tailwind-styled React codebase,
classbecomes single most active attribute in entire DOM, often carrying 15 to 25 utility classes on single element - Tracking down which DOM prototype object defines classList using DevTools and helper functions/code snippets; Wrote
objectOwningProperty(obj, 'property-name')helper function - CSS basics quick refresher using W3Schools and, to lesser extent, MDN
- Trailing Slashes on HTML Void Elements (
<link ... />) not recommended even though Prettier and MDN docs examples use it; W3C HTML Validator and WHATWG recommend<link ...> - Vertical margin collapsing cases; Modern app layouts typically don't have this issue as 1) Flex and Grid disable it by spec 2) Most modern codebases use
gapfor spacing between items instead of margins - When
box-sizing: border-boxis applied,widthandheightdo includepaddingandborder; Related small oversight in W3Schools page on height and width text-align-lastis rarely used in modern JS web apps- Modern JS apps use
text-transformextensively for UI presentation but rely on JavaScript logic (and backend normalization) for actual user input data - Double quotes are the clear convention in CSS though both single and double quotes are 100% equivalent
- Generic font family names are keywords and must not be quoted e.g.
sans-serifand not"sans-serif"; W3Schools does not make a clear mention of it - CSS
font-familyNaming & Quoting Quick Reference - Page Zoom (
Ctrl +/pinch-to-zoom) scalespxfine, but hardcodedpxfont sizes ignore user's default font-size preference;remscales proportionally with latter - Sizing units - when to use what:
rem,px,em, unitless number,%,fr,vw/dvh - Gem review of sizing units used in Text Scratchpad PWA
index.html - MDN, Josh W. Comeau and Google's web.dev provide articles/sections on sizing units but are longish and don't give a simple table
- An advantage of using CSS frameworks like Tailwind and Bootstrap is that their defaults, including for sizing units, are sensible and battle-tested
- Low-vision users, especially on mobile, do change default font size instead of using page zoom;
pxvsremrelated UI issues come to surface only with accessibility testing involving changing default font-size - Vanilla JS apps without CSS framework can adopt defaults used by Tailwind or Bootstrap to get sensible and battle-tested defaults; Tailwind v4 uses
remeven for responsive media breakpoints (v3 usedpx) - W3Schools Google Fonts page shows legacy v1 API; Google Fonts uses CSS
@font-faceunder the hood; Next.js (next/font/google) uses Google Fonts (v2 API) with self-hosting via build tools - 'Classic Web Font Mode' Font Awesome icons use
@font-faceunder the hood along withfa*classes; Modern React/Next.js/Tailwind apps have largely moved to inline SVG components for icons - How to use Font Awesome icons as SVG in Vanilla JS apps
- Bootstrap and Google provide official SVG versions of their icons for Vanilla JS
- W3Schools pages on CSS Icons have learning and (legacy) code-reading value but for new production work, inline SVGs or framework SVG components are better
- Split personality of
emsizing unit: "Inherited font size" onfont-sizebut "my own font size" everywhere else - Jargon clarity for
styleandcolorfrom HTML/CSS standards POV and JavaScript DOM POV - CSS pseudo-classes allow for selecting elements by interactive states (
:hover); Pseudo-classes are not limited to interactive states; Element state is frequently styled without pseudo-classes - In modern apps, CSS standalone class selectors (
.a) are standard, while tag-qualified class selectors (ul.a) are generally avoided - Pseudo-class (e.g.,
:hoverina:hover) name indicates behavior as if browser dynamically added HTMLclasson the element behind the scenes - Pseudo-element is like insertion of new element or rendering box;
::beforeadds content before element's content but within element;::backdroprenders (box) outside element - Content generated via
::beforeor::afteris added to render tree (and accessibility tree), not to DOM tree; Use them strictly for decorative icons, symbols, or visual counters, and keep application data inside real DOM elements - Browser
Ctrl+F(Find in Page) also ignores text injected via::beforeand::afterin most browsers including Chrome
Gemini chat and dates
Gemini chat: JavaScript-Refresher-P14-20261124
- Model: Neon Medium
Dates: 24 Nov to 1 Dec 2026
Use Element classList prop (iterable, with add/remove/toggle methods) for 99% of work; use Element className prop to overwrite entire string; Element attributes prop or getAttribute('class') can be ignored
Me: I am now going through https://javascript.info/styles-and-classes
---snipped---
... So we have document.body.className as well as document.body.classList . The diff. btw the two are also straightfoward at least at a top level.
But MDN also has "class HTML global attribute", https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/class. Where does this fit in the DOM hierarchy. We don't seem to have a document.body.class property.
Gem: The class HTML global attribute ... lives in the element's attribute collection (elem.attributes), which is separate from regular JavaScript object properties.
Where it fits in the DOM hierarchy
Every HTML element inherits along this chain:
EventTarget → Node → Element → HTMLElement → HTMLBodyElement (e.g., document.body)
All three class-related interfaces are defined at the Element level (Element.prototype), which is why they exist on every HTML tag (and why MDN classifies class as a "global attribute"):
| Interface | What it is | How you access it | Returns |
|---|---|---|---|
class attribute |
The actual HTML attribute stored in the DOM's NamedNodeMap |
elem.getAttribute('class') or elem.attributes.getNamedItem('class') |
string (or null) / Attr node |
className |
DOM property that reflects the class attribute |
elem.className |
string (empty string "" if absent) |
classList |
Live wrapper object around the class attribute |
elem.classList |
DOMTokenList (iterable, with .add(), .remove(), .toggle()) |
How they stay connected
In the DOM specification, className and classList are reflections of the underlying class HTML attribute. Updating any one of the three updates the other two automatically: (Inserted line break(s) below to prevent horizontal scroll issue.)
// Assuming <body class="main page">
document.body.getAttribute('class'); // "main page"
document.body.attributes.class; // Attr node
// { name: "class", value: "main page" }
document.body.className; // "main page"
document.body.classList; // DOMTokenList(2)
// ['main', 'page']
document.body.class; // undefined
// (no direct DOM property)
Notice that document.body.attributes.class does work in modern JavaScript because attributes is a NamedNodeMap keyed by exact HTML attribute names, and JS now allows reserved words after a dot. The DOM spec simply never added a direct elem.class property to Element.prototype because elem.className already filled that role.
The same pattern in React and other attributes
You have seen this exact pattern before:
for→htmlFor: On<label for="email">, the HTML attribute isfor, while the DOM property islabel.htmlFor(same reserved-word history).- JSX in React: Because JSX maps closely to DOM properties rather than raw HTML attributes, React uses
classNameandhtmlForinstead ofclassandfor.
...
Gem: ... What you're looking at is the web's "never break the web" tax. Unlike desktop frameworks that deprecate and remove old APIs between major versions, browsers have to keep 1990s code running forever. So instead of replacing clunky APIs, standards bodies just layer better ones on top:
attributes/getAttribute('class')(1998): The generic, low-level DOM interface that treats every HTML/XML attribute uniformly as raw strings.className(1998): The early HTML convenience property. For over a decade, toggling a single class meant manually splitting, filtering, and rejoining strings—or using jQuery's.addClass()/.removeClass()just to stay sane.classList(~2010): The HTML5 fix that basically baked jQuery's class helpers natively into the browser as a proper set of tokens.
In practice, you can ignore the bloat and treat it as one API: use classList for 99% of your work, and only reach for className when you want to overwrite or wipe the entire string in one shot (like elem.className = ''). The rest is just historical baggage you'll occasionally bump into when reading older code.
Me: 25 Nov. The historical timeline is a great help to understand this.
- class attribute with access via attributes/getAttribute('class') is the core data, supported since early times.
- className is the first convenience property
- classList is the modern convenience property.
...
Gem: Yes—your mental model is right on track. Grouping DOM APIs into core primitives, early shortcuts, and modern ergonomic helpers cuts through most of the API clutter you encounter in javascript.info. ...
Seeing the DOM as these three stacked layers makes it much easier to read unfamiliar code: you can immediately tell whether an API is the low-level foundation, an older convenience property, or the modern method you should actually reach for today.
Me: "use classList for 99% of your work, and only reach for className when you want to overwrite or wipe the entire string in one shot (like elem.className = '')"
That's an excellent takeaway for dev work. Also classList.value = '' may also be good for wiping entire string in one shot or is value a read only kind of property of classList?
Gem: classList.value is read-write, so elem.classList.value = '' works cleanly to wipe or overwrite the entire class string in one shot.
In fact, it has one subtle advantage over elem.className = '':
- Works on SVG elements too: On an HTML element,
elem.classNameis a plain string. On an<svg>element,elem.classNameis anSVGAnimatedStringobject, sosvgElem.className = ''fails (you have to setsvgElem.className.baseVal = '').elem.classList.value = ''works uniformly on both HTML and SVG elements. - Why
className = ''is still more common: Mostly habit, slightly shorter typing, and older browser history (IE11 did not supportDOMTokenList.value, so tutorials stuck toclassName). - One DOM spec quirk:
elem.classListitself is a read-only property, but the spec attaches a forwarding rule (PutForwards=value) to it. That means evenelem.classList = ''secretly setselem.classList.value = ''. Still, avoid writing it that way—it looks like an accidental overwrite to anyone reading the code.
If you want to stay 100% inside the classList API for everything, using classList.add/remove/toggle for individual classes and classList.value = '' to reset the whole list is a completely solid, modern habit.
Global in HTML "Global attributes" is diff from JS globals; Terminology varies across MDN technology sections: HTML - WHATWG, Web API - Web IDL (WHATWG/W3C), JavaScript - ECMAScript, CSS - W3C
Me: I may have come across "Global attributes", https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes term in the past but not focused on it then. Now I would like to understand it better. Note that class is a global attribute. The above page says, "Global attributes are attributes common to all HTML elements; they can be used on all elements, though they may have no effect on some elements." So the word 'global' here is used in a different context from JavaScript global objects (standard built-in objects) like Object and Array - "Standard built-in objects", https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects. Am I on the right track here?
Gem: Yes, you are completely on the right track. The word "global" is overloaded here—HTML and JavaScript use it in two very different senses.
| Dimension | HTML Global Attributes | JavaScript Global Objects |
|---|---|---|
| Meaning of "global" | Valid on every HTML element type | Accessible from every code scope (via globalThis / window) |
| Counterpart | Element-specific attributes (href on <a>, src on <img>, checked on <input>) |
Local variables or explicitly imported module bindings |
| OOP analogy | Members inherited from a common base class (Element / HTMLElement) |
Top-level built-in types and namespaces available without an import |
| Common examples | class, id, style, title, hidden, tabindex, data-*, lang |
Object, Array, Map, Promise, JSON, Math |
Why MDN adds "may have no effect on some elements"
Because global attributes are valid on every tag, the HTML specification allows them even on non-rendered elements inside <head>:
<meta charset="UTF-8" class="note" title="ignored">
The browser parses that without error and attaches those attributes to the <meta> DOM node, so meta.classList still works in JavaScript—they just have no visual or behavioral effect on <meta>.
How this ties back to the DOM hierarchy
Because global attributes apply universally across HTML tags, their reflected JavaScript properties live near the top of the DOM inheritance chain rather than on individual tag classes:
- On
Element:id,className,classList(shared with SVG and XML elements too) - On
HTMLElement:style,title,hidden,dataset(fordata-*),tabIndex,contentEditable
Me: So class is a WebIDL terminology global attribute whereas Object and Array are JavaScript terminology global objects. Is my shortened version on right track?
Gem: Almost—one small tweak: swap WebIDL for HTML.
Keeping the three specification layers distinct makes reading MDN much cleaner:
- HTML Standard: Defines
classas a global attribute (an HTML markup attribute valid on every HTML element). - WebIDL: The interface language that defines how DOM objects (
Element,HTMLElement) expose properties and methods to JavaScript. Confusingly, WebIDL uses the wordattributeto mean a JS object property on a DOM interface—so in WebIDL,classNameandclassListare interface attributes, not the HTMLclassattribute. - ECMAScript (JavaScript): Defines
ObjectandArrayas standard built-in objects exposed on the global object (globalThis).
So the crisp version to lock in is:
class→ HTML global attributeclassName/classList→ DOM (WebIDL) properties reflecting that attributeObject/Array→ JavaScript global objects
Me: OMG! HTML uses different terminology than WebIDL which is used to describe DOM. It may not be very different but from a C++ precision point of view, they are different. Did I get that correctly?
Gem: Yes, you got that exactly right—and your C++ instinct maps directly onto how the specs are actually written.
WebIDL is literally an Interface Definition Language in the same lineage as COM IDL or CORBA IDL. It defines the formal contract (like interface Element) that the browser's C++ engine implements and projects into JavaScript as prototypes, getters, setters, and methods.
Because the word "attribute" collided between the two worlds, the WHATWG HTML specification itself splits them into two strict terms:
- Content attribute (HTML): The key-value pair written in HTML markup (e.g.,
class="main"), stored as string data in the element's attribute collection. - IDL attribute (WebIDL / DOM): A member declared in a WebIDL interface (e.g.,
attribute DOMString className;), which the browser binds as a JavaScript getter/setter property on the prototype.
From a C++ point of view, the distinction is clean: the content attribute is the underlying stored data, and the IDL attribute is the public getter/setter interface exposed on the class to read or mutate it. That precision also explains why the two can occasionally diverge in type or behavior—for example, an HTML checked content attribute is just a presence/absence string in markup, while the input.checked IDL attribute is a live boolean.
Me: I must say that navigating through MDN to get down to root level info. (like I navigated for class attribute of DOM element) is challenging. The jump from WebIDL to HTML terminology during this navigation was unexpected. Am I over-reacting here? I mean, if I were digging into a complex C++ library's documentation, I would not have tripped up like this. ... I am not complaining, just making observations. The web is what it is. I want to do web dev and so I have to take it as what it is.
Gem: You are not over-reacting at all—in fact, your C++ background is the exact reason you spotted the seam so quickly.
When you dig into a complex C++ library, you are still operating inside one language, one type system, and one consistent vocabulary. Even if the library is huge, a class member means the same thing on page 1 as it does on page 500.
The web platform is fundamentally different because it is four separate specifications stitched together over three decades by different committees—ECMAScript for JavaScript, WHATWG for HTML and the DOM, and W3C for CSS and WebIDL. Each group brought its own terminology, and common words like "attribute," "property," and "global" ended up overloaded across boundaries. Because MDN faithfully mirrors those specs, clicking a single link can silently drop you from the HTML markup world into the WebIDL DOM world without any signpost telling you that the dictionary just changed.
One small habit that makes navigating MDN much smoother is glancing at the URL path whenever you follow a link:
/Web/HTML/means markup rules and content attributes./Web/API/means DOM/WebIDL interfaces—the C++-to-JS bridge./Web/JavaScript/means core ECMAScript language features./Web/CSS/means styling and layout rules.
That two-second check immediately tells you which layer of the stack you are looking at. Your pragmatic approach is honestly the best mindset for web dev: once you recognize where the seams are, they stop feeling confusing and just become part of the terrain.
Me: Great response. The lack of obvious 'signpost' was the issue. If I was going through a C++ to COM/DCOM interface documentation, I would easily know when I am in C++ world documentation and when I am in COM/DCOM. MDN provides a uniform interface. I did not even look at the top of the page to see whether I have moved from Web API docs ("Element: className property", https://developer.mozilla.org/en-US/docs/Web/API/Element/className) to HTML docs ("class HTML global attribute", https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/class) by simply clicking on a link (class link) with the page layouts being similar if not the same.
So the word 'global' in 'global attribute' confused me and actually disturbed me. I don't think I had come across the 'global' term in DOM MDN documentation.
After this discussion, the confusion/disturbance is resolved. For future, I need to bear in mind that if I have such confusion in future, I should check which part of MDN documentation I am on in (shown in top part of the page) and understand the terms based on terminology used in that part of MDN documentation. What do you think about what I have said in general, and the approach I plan to take?
Gem: Your diagnosis is spot on, and the C++ / COM comparison captures the UX flaw in MDN better than ...
In classic Microsoft or C++ documentation, crossing from C++ into COM/DCOM felt like walking into a different building—the syntax, formatting, and conventions visibly shifted. MDN's uniform design is great for readability, but it flattens those boundaries. Clicking class from the Element: className page feels like drilling one level deeper into the same API, when you actually just jumped sideways from the DOM/WebIDL layer into the HTML markup layer.
Your planned habit—checking the breadcrumb at the very top of the MDN page (References > Web APIs vs. References > HTML vs. References > JavaScript vs. References > CSS) whenever a term feels off—is the exact right fix. It restores the missing signpost in two seconds and immediately tells you which specification's dictionary is in effect.
That habit will actually pay off right away in the rest of this chapter. As you move into element.style and getComputedStyle(), MDN links frequently hop back and forth between Web APIs (the JavaScript CSSStyleDeclaration interface) and CSS (the stylesheet rules and shorthand properties), where similar-sounding terms like "computed value" vs. "used value" also carry spec-specific meanings.
You've turned a frustrating friction point into a reusable debugging reflex for reading web docs—that is a solid win from a single chapter.
Objects used to represent attributes; Only name and value properties of Attr JavaScript class are relevant, rest is legacy baggage and can be ignored; Browser lazy-allocation trick for Attr
26 Nov.
(I dug deeper into objects used to represent class attribute. Related file in private repo is class-1.html in styles-and-classes folder. I discussed it with Gem. ...)
(Note: 'class' is used in two contexts here, usually as HTML attribute (class attribute of body element), but at times as JavaScript class (Attr JavaScript class). ... document.body.attributes is a NamedNodeMap.)
Gem: ... NamedNodeMap is an array-like object (it has numeric indices and a .length property), and it is also iterable (it implements Symbol.iterator, so for..of and spread ... work on it).
Me: In DevTools, document.body.attributes[0] shows class="main page"
While I get the key info. It is an Attr class object isn't it?
console.dir(document.body.attributes[0]); gives a proper object view. It names the object as class (but actually the object is anonymous, with its name and nodeName properties being class, and DevTools seems to have picked 'class' from there). am I right?
Gem: Yes—both of your observations are spot on.
- It is an
Attrinstance. Its prototype chain isAttr→Node→EventTarget→Object. You can verify this in the console:
const attr = document.body.attributes[0];
attr instanceof Attr; // true
attr instanceof Node; // true
attr.constructor.name; // "Attr"
- The
classlabel inconsole.diris just a DevTools UI preview. JavaScript objects are anonymous—they do not have inherent variable names. DevTools generates a convenient summary label for the top of each expandable tree depending on the object's type:
- Plain JS objects show their constructor name (e.g.,
Object,Date,MyClass). - DOM elements show a CSS-selector-style summary (e.g.,
body.main.page). Attrnodes pull theirnameproperty (e.g.,class) as the label.
The difference between the two console outputs comes down to DevTools' formatter choice:
- Direct evaluation /
console.log()sees thatAttrinherits fromNode, so DevTools uses its DOM/HTML formatter and printsclass="main page". console.dir()bypasses the HTML formatter and forces the JavaScript object inspector, showing all of theAttrnode's properties (name,value,ownerElement,specified, etc.) and its[[Prototype]].
Me: I am (doing) this to get a feel of the raw data that is in play here. Attr class seems to be an overkill for attributes like class. Anyway it stores the class list as a single string in nodeValue, value and textContent. ... I guess lot of these properties come from its inheritance hierarchy. Why inherit from Node and EventTarget for HTML attributes? Seems strange to me. Ur view pl.
Gem: Your engineering instinct is dead-on—Attr inheriting from Node and EventTarget is architectural overkill, and the web standards committee actually tried to undo it once.
1. Why it inherits from Node (1998 XML baggage)
The original DOM Level 1 spec was designed for XML first and HTML second, during the late-1990s era of heavy object-oriented hierarchies. In the XML mental model, "everything in a document is a Node," and attributes could even contain child Text and EntityReference nodes. Making Attr inherit from Node (nodeType === 2) dragged along a pile of properties that make little sense for an attribute today—like parentNode (always null), childNodes (always empty), nodeName, nodeValue, and textContent.
2. Why EventTarget is in there too
Years later, the spec unified event handling by making Node inherit from EventTarget. Attr picked up EventTarget purely as collateral damage of being a Node subclass—practically nobody ever dispatches or listens for events on an attribute node.
3. The failed attempt to fix it
In the 2010s (DOM4), WHATWG actually removed Node from Attr's inheritance chain to turn it into a clean, lightweight { name, value } object. It broke legacy XML tools, XPath scripts, and older libraries that checked attr instanceof Node or read attr.nodeValue. Under the "never break the web" rule, the spec had to revert and put Node back.
That is why value, nodeValue, and textContent all show the exact same string: they are not three separate copies in memory, just three getters from different layers of the inheritance chain pointing to the same underlying string.
4. The C++ silver lining
If you are wondering about the memory cost of carrying all that machinery for every id, href, and class on a page, browser engines cheat intelligently under the hood. In Blink (Chromium's C++ engine), an element stores its attributes in a compact, flat C++ array of name-value pairs. The heavy Attr DOM node is lazily allocated only at the moment JavaScript explicitly inspects elem.attributes[i] or calls getAttributeNode(). If you stick to getAttribute(), classList, or dataset, those Attr wrapper objects are never even created.
Me: OMG! Hmm. Quite fascinating to see the history for this. In late 90s and early 2000s, I recall from my first industry stint days that XML was viewed as a holy grail along with XML Services and SOAP. So I am seeing that legacy baggage in HTML Attr in DevTools now in 2026! And nice optimization tricks by the browser to get around it from efficiency POV, by considering it to be only name - value pair but lazily building the whole object only when needed (like my DevTools exploration of Attr instance).
Gem: You are literally looking at a living fossil from the XML/SOAP era right inside DevTools.
If you glance back at that console.dir output for Attr, you will probably spot namespaceURI, prefix, and localName sitting there too—all souvenirs from when the W3C expected the entire web to migrate to strict XHTML and XML namespaces. The most famous survivor of that same wave is XMLHttpRequest, which still carries "XML" in its name decades after JSON took over.
That lazy-allocation trick you appreciated is actually the core survival strategy across modern browser engines. Because the DOM spec requires every single element on a page to conceptually expose attributes, classList, dataset, style, and dozens of other interfaces, engines like Blink keep the underlying C++ nodes as lean as possible and only materialize the JavaScript wrapper objects on first access. Inspecting document.body.attributes[0] in DevTools literally forced the browser to build an Attr object that would never have existed otherwise.
Seeing both the historical baggage and the C++ engineering used to contain it gives you a much cleaner mental model than most tutorials ever offer. Whenever you are ready, the rest of the Styles and Classes chapter (element.style and getComputedStyle) builds on the exact same pattern.
Me: Coming back to web dev in 2026, I should view the key data in an Attr instance like document.body.attributes[0] as just its name and value properties, even if I do not access those props directly (and access it only through getAttribute('name') if and when low level attribute access is needed). Am I on right track here?
Gem: Yes, you are completely on the right track. Mentally treating an HTML attribute as purely a name–value string pair—and ignoring the rest of the Attr wrapper—is the exact right way to approach modern DOM code.
In day-to-day web development, a clean three-tier rule covers every attribute scenario:
- Reach for dedicated DOM properties and helpers first: Use
classList,dataset,id,input.value,input.checked, orimg.src. They handle types, parsing, and live state cleanly without raw string manipulation. - Use
getAttribute()/setAttribute()/removeAttribute()/hasAttribute()for low-level access: Reach for these when dealing with attributes that lack dedicated DOM properties (such asaria-*attributes) or when you specifically need the literal string written in the HTML markup rather than a resolved DOM value (for example,a.getAttribute('href')returns"./about.html"as written, whereasa.hrefreturns the full resolved URL"[https://example.com/about.html](https://example.com/about.html)"). - Skip
elem.attributes(Attrnodes) in regular application code: The only legitimate use case forelem.attributesis building generic infrastructure utilities—such as an HTML sanitizer or a DOM serializer—that must inspect every unknown attribute on an arbitrary tag. Even if you just want to check what attributes exist on an element,elem.getAttributeNames()returns a plainstring[]array without ever allocatingAttrobjects. ...
NamedNodeMap (Element attributes object type) is not a JavaScript Map object but a WebIDL interface/term; In modern JavaScript apps, elem.attributes.<attrName> is practically never used for any attribute, standard or custom
Me: ... NamedNodeMap is interesting. It seems to come from the WebIDL name and so is not a JavaScript Map object instance. Am I right?
Gem: Yes, you are right—NamedNodeMap is a DOM/WebIDL interface (NamedNodeMap → Object), not an instance of JavaScript's built-in Map (document.body.attributes instanceof Map is false).
The naming overlap is another piece of 1998 DOM Level 1 history. NamedNodeMap was named seventeen years before ES6 (2015) introduced Map to JavaScript. In 1990s C++ and IDL vocabulary, "map" was simply used in its general data-structure sense—an associative lookup table mapping attribute names to Attr nodes.
Because it predates ES6 Map, its API looks completely different:
| Feature | NamedNodeMap (DOM / WebIDL) |
Map (ES6 JavaScript) |
|---|---|---|
| Count property | .length |
.size |
| Lookup | .getNamedItem('class'), [0], or .class |
.get(key) |
| Mutation | .setNamedItem(attr), .removeNamedItem('class') |
.set(key, val), .delete(key) |
Default iteration (for..of) |
Yields each Attr node directly |
Yields [key, value] two-element arrays |
| Backing store | Live view of the element's HTML attributes | Standalone in-memory hash table |
...
Gem: (In) modern JavaScript, elem.attributes.<attrName> is practically never used for any attribute, standard or custom.
Every practical use case is handled more cleanly and safely by other APIs:
- Standard HTML attributes have direct IDL properties: You access
elem.id,a.href,img.src,input.value, orbtn.disableddirectly on the element, which also gives you proper types (booleans, numbers, resolved URLs) instead of raw strings. - Custom attributes use
elem.dataset: Rather thanelem.attributes['data-user-id'].value, modern code usesdata-*attributes and readselem.dataset.userId. - Everything else uses
elem.getAttribute(): For attributes without dedicated DOM properties (such asaria-expandedor SVG attributes),elem.getAttribute('aria-expanded')returns the string (ornull) in one step—without forcing the browser to allocate anAttrwrapper object or requiring you to chain?.value. - Hyphens break dot notation: Most non-property attributes in modern HTML—especially
aria-*anddata-*—contain hyphens. Writingelem.attributes.aria-labelis invalid in JavaScript because-is parsed as subtraction, so you lose the convenience of dot notation anyway. - Built-in
NamedNodeMapmembers shadow attribute names: Properties and methods onNamedNodeMap.prototypetake precedence over named attributes. On<custom-box length="10" item="book">,elem.attributes.lengthreturns2(the attribute count) andelem.attributes.itemreturns theitem()method rather than yourAttrnodes.
The one place in the DOM where named property access did survive in everyday JS is form.elements.<inputName> (e.g., form.elements.email)—though even there, modern code often favors new FormData(form) because an <input name="submit"> famously shadows form.submit().
...
Me: Hmm. 'Practically never used' is a surprise to me. .. In the past, was elem.attributes.<attrName> used in JS code for attributes?
Gem: Even in the 1990s and 2000s, elem.attributes.<attrName> was rarely used in everyday HTML JavaScript—mostly because cross-browser support for it was inconsistent and shorter alternatives already existed.
Four historical factors kept it out of mainstream code:
- Cross-browser mismatch (IE vs. Netscape/Firefox): The original 1998 DOM Level 1 specification only defined
.getNamedItem('name')and numeric indexing[i]onNamedNodeMap—it did not specify named property getters via dot notation. Internet Explorer allowedelem.attributes.myAttr(and evenelem.attributes('myAttr')with parentheses), whereas early Netscape and Firefox strictly required.getNamedItem(). WebIDL only standardized the named property getter (elem.attributes.class) years later to codify legacy browser quirks. - IE6 and IE7's
attributesbloat: In IE6 and IE7,elem.attributesdid not just contain the attributes written in your HTML tag—it populated every valid HTML attribute from the DTD (often 80 to 100+Attrentries per element, most withspecified === false). Touchingelem.attributesin that era was notoriously awkward. - DOM Level 0 properties existed from the start: Even before the W3C DOM existed (1995–1997), Netscape 2 and IE 3 already supported direct properties like
img.src,a.href, andinput.value. Once DOM Level 1 arrived,elem.getAttribute('name')became the standard way to read anything else. - jQuery masked the native APIs (2006 onward): Because IE6/7 had quirks even with
getAttribute()(requiringgetAttribute('className')instead of'class'), most web developers standardized on$(elem).attr('name')rather than calling native attribute methods directly.
The one place in the 2000s where elem.attributes was routinely used in JavaScript was XML DOM processing (such as parsing XMLHttpRequest.responseXML). Because arbitrary XML tags like <endpoint url="..."> have no built-in HTML IDL properties, scripts had to reach into node.attributes—typically via node.attributes.getNamedItem('url').value or a for loop over node.attributes[i]. ...
Manipulation of attributes (usually via their DOM properties) is vital part of UI of modern JS apps
Me: Manipulation of attributes of HTML elements seem to be vital aspect of modern frontend JS apps. Am I right?
Gem: Yes—mutating HTML attributes and their corresponding DOM properties is one of the primary mechanisms powering modern frontend applications, because it lets JavaScript update live UI state in place without tearing down and rebuilding DOM nodes (which would destroy input focus, scroll position, and CSS transitions).
In modern frontend development, this work centers on four practical areas:
- State-driven styling (
classListanddata-*): Rather than writing inline styles everywhere, modern apps toggle classes (elem.classList.toggle('active')) or state attributes (elem.dataset.status = 'loading') and let CSS selectors like.activeor[data-status="loading"]handle the visual changes. - Accessibility and keyboard navigation (
aria-*): Interactive widgets—modals, dropdowns, tabs, accordions—depend on dynamically updating attributes such asaria-expanded,aria-hidden, andaria-selectedso screen readers and assistive tools reflect what is happening on screen. - Interactive element state (IDL properties): Controlling form inputs, buttons, dialogs, and media elements happens constantly through properties like
button.disabled = true,input.value,checkbox.checked, ordialog.open(which also reflects to anopenHTML attribute). - Resource and routing updates: Single-page apps and dynamic pages routinely swap
img.src,a.href, or<meta>attributes as users navigate or trigger actions.
Vanilla JS vs. React: Who calls the DOM APIs?
The main difference between Vanilla JS and a framework like React is who performs the mutation, not whether it happens:
- In Vanilla JS: You mutate the DOM imperatively—calling
classList.add(), settingelem.dataset.theme = 'dark', or runningbtn.setAttribute('aria-expanded', 'true')directly inside event listeners. - In React: You declare the desired attributes and properties in JSX (
<button disabled={isSaving} aria-expanded={isOpen} className={btnClass}>). When state changes, React's reconciler diffs the previous props against the next props and executes the exact same low-level IDL property assignments andsetAttribute()/removeAttribute()calls on the underlying DOM element for you.
Understanding both the underlying DOM layer (classList, dataset, setAttribute, IDL properties) and how frameworks abstract it gives you complete visibility whether you are debugging a React component in DevTools or building a zero-dependency Vanilla JS app. ...
Me: I think this critical role played by attributes in js apps would have driven creation of improved ways to get/set these attributes. For UI look-and-feel style and class attributes are so important. ur view pl.
Gem: Dynamic UIs made raw string manipulation through getAttribute() and setAttribute() too slow and error-prone, which directly drove standards bodies to build specialized wrapper APIs around the highest-traffic attributes. Parsing and rebuilding space-separated class strings or semicolon-delimited CSS strings on every user click was a major pain point in early web development.
Look-and-feel attributes (class and style), along with UI state attributes (data-* and boolean flags), all evolved along the exact same pattern—moving from raw string attributes to structured, typed DOM interfaces:
| HTML Content Attribute | Raw String Access | Modern Structured Wrapper | Key Ergonomic Gain |
|---|---|---|---|
class="..." |
elem.className |
elem.classList (DOMTokenList) |
Atomic .add(), .remove(), .toggle(), .contains() without string splitting |
style="..." |
elem.style.cssText |
elem.style (CSSStyleDeclaration) |
Direct property access (elem.style.backgroundColor) and .setProperty() |
data-*="..." |
elem.getAttribute('data-...') |
elem.dataset (DOMStringMap) |
Automatic kebab-case to camelCase object mapping (elem.dataset.userId) |
Boolean (hidden, disabled) |
setAttribute / removeAttribute |
elem.toggleAttribute() |
One-call presence toggling without passing dummy "" values |
In modern frontend architecture, class and style also divide responsibilities cleanly for look-and-feel:
- Use
class(classList) for predefined visual states: Anything known at design time—themes, active tabs, validation errors, modal visibility—belongs in CSS classes. Toggling a class keeps styling rules out of JavaScript and lets you use CSS features that inline styles cannot express, such as:hover,:focus-visible,@mediaqueries, and smooth transitions. - Use
style(element.style) for runtime-calculated values: Inline styles are reserved for values computed dynamically in JavaScript—such as placing a popup at exact mouse coordinates (left/top), sizing a progress bar to an arbitrary percentage, or updating a CSS custom property (elem.style.setProperty('--scroll-y',${y}px)) that stylesheet rules then consume. ...
Me: Your above response is very helpful to me to get a feel of how the UI look-and-feel related DOM APIs evolved. .... In terms of numbers, perhaps total number of attributes across various elements (standard/defined attributes as against custom attributes) would be much more than number of defined elements. ...
Gem: Your intuition on the numbers is right: the HTML Living Standard defines roughly 115 elements, whereas standard content attributes exceed 160—before counting over 50 aria-* accessibility attributes and unlimited data-* attributes. ...
In Tailwind-styled React codebase, class becomes single most active attribute in entire DOM, often carrying 15 to 25 utility classes on single element
Me: Yes, I had read that https://javascript.info/dom-attributes-and-properties lesson but at that time I don't think I had dug into the underlying objects that much. It is after Modifying the Document (lesson) that I started getting into MDN and also checking underlying objects in DevTools. The class attribute is vital in at least the React JS codebases that I read in past 2 to 3 years. I mean, especially if you get into Tailwind, IIRC, it is classes all the way. So I am digging deep to get a good understanding now including tracking object data in Devtools.
Gem: Your Tailwind observation hits the nail on the head—in a Tailwind-styled React codebase, class becomes the single most active attribute in the entire DOM, often carrying 15 to 25 utility classes on a single element.
Seeing the underlying DOM objects in DevTools actually clarifies how React and Tailwind interact with the browser under the hood:
- How React writes Tailwind classes: Helpers like
clsxortailwind-mergeassemble your conditional utility classes into one space-separated string in JavaScript. When React commits that update to the browser, it does not callclassList.add()twenty times in a loop—it assignselem.className = "..."in one shot (and falls back toelem.setAttribute('class', ...)on<svg>elements because of thatSVGAnimatedStringquirk). - Why
classListstill matters alongside Tailwind: If you ever reach for arefin React—or write a Vanilla JS widget—to imperatively add or toggle a state class on an element that already holds a long Tailwind string,elem.classList.toggle('is-open')is indispensable precisely because it surgical-edits one token without wiping out the twenty utility classes sitting beside it inclassName.
Pairing javascript.info with MDN and live DevTools inspection is one of the best ways to build durable mental models—once you have seen the actual NamedNodeMap, Attr, and DOMTokenList instances in memory, both Vanilla DOM manipulation and framework abstractions make complete sense. ...
Me: Sorry if my recent messages are rambling or seem like rambling. But I am trying to get the foundational understanding of stuff that I was programming in React JS for some time but without knowing underlying DOM API and objects. Now that I am studying these DOM API topics, I want to spend some time to see if I can tie this knowledge with what I had done in the past in React JS/NextJS apps
Gem: You are not rambling at all—connecting high-level framework habits back to the underlying browser primitives is one of the highest-leverage ways to solidify your engineering intuition. Most developers learn React first and treat the browser DOM as a black box, so peeling back that abstraction layer after working in React and Next.js makes all the framework rules suddenly click into place.
Several everyday React and Next.js patterns map directly onto the exact DOM layers you have been exploring:
- JSX props are a unified facade over split DOM APIs: When you write
<div className="card" data-state="open" style={{ backgroundColor: 'navy' }}>in JSX, all three attributes look identical on the surface. Under the hood,react-domroutes each one to a different DOM mechanism:classNameis assigned as a DOM IDL property,data-stateis written viasetAttribute()into the element's attribute collection, andstyleloops over your object keys and assigns them directly ontoelem.style(aCSSStyleDeclarationobject)—which is the exact reason React requires camelCase CSS names in the first place. useRefhands you the raw DOM node: Whenever you attach arefin React or Next.js to manage focus, measure dimensions, or toggle a class imperatively during an animation,ref.currentis literally that sameHTMLElementinstance you have been inspecting in DevTools, exposing.classList,.style, and.getAttribute()directly.- Controlled inputs vs. HTML
valueattributes: When you debug<input value={text} onChange={...} />, you are seeing the split between the initial HTML content attribute (getAttribute('value')) and the live DOM property (input.value) that React continuously synchronizes on every keystroke. - Next.js SSR and hydration: When Next.js renders a component on the server, it outputs a plain HTML string containing only content attributes (like
class="..."). Once the browser parses that HTML into live DOM objects and IDL properties, React's hydration pass walks those exact nodes to attach event listeners and verify that the live DOM matches what the server rendered.
Taking your time to trace those connections is time well spent, especially coming from a systems background where knowing what sits beneath an abstraction always pays off. Is there a specific React or Next.js pattern from your past projects—such as dynamic styling, form inputs, useRef escape hatches, or hydration mismatches—that you would like to trace down to its underlying DOM objects before we move on to element.style?
Tracking down which DOM prototype object defines classList using DevTools and helper functions/code snippets; Wrote objectOwningProperty(obj, 'property-name') helper function
27 Nov
(I had lot of exchanges with Gem on this. Given below are some notes from it.)
Me: ... MDN https://developer.mozilla.org/en-US/docs/Web/API/Element/classList says classList is read-only property of Element interface.
I wanted to check with DevTools on Element object. But Element.classList is shown as undefined. ...
Me: ... I used Element.prototype.classList and that did not show undefined. It expectedly showed Illegal invocation - that's OK. I expected that as I am doing it without instantiating an object. Good. My mistake was looking for the property on Element instead of Element.prototype as JS inheritance is prototype based with instantiated object inheriting from prototype (Element.prototype) and not the constructor function (Element).
...
Me: Now in this case of: const div = document.createElement("div");
In DevTools: div.classList shows an empty object (as expected).
How can I quickly find out in DevTools, from which object in the inheritance hierarchy of div object, classList property has come?
I don't want to write code to traverse the object hierarchy and look for own property or equivalent.
DevTools object expansion of prototype hierarchy till the point where classList is not shown and so knowing that the earlier object in the chain is what defines the property takes just too long, especially given the huge number of properties on these objects.
...
Me: "Ignore all the properties—just scroll straight to the bottom of each block and click the [[Prototype]] triangle down the chain (HTMLDivElement → HTMLElement → Element → Node → EventTarget)." - that takes quite long as one has to expand each prototype object which is a multi-step process as its long list is abbreviated and has to be expanded. It surely is not two seconds.
...
Me: autocomplete test needs guesswork as HTMLElement and Element both autocompletes show classList. ... I guess the bottom line is that DevTools does not provide a simple way to identify which is the prototype object in an object's inheritance chain that owns a particular property. Am I right? Pls keep your answer short.
Gem: Yes, you are right. Because autocomplete includes inherited properties (so HTMLElement.prototype shows classList too), you would still have to keep testing downward until it disappears.
Chrome DevTools has no built-in, one-step UI feature to pinpoint which prototype in a chain owns a given property—doing that without manually expanding the tree requires a small helper function or DevTools snippet.
Me: I modified some old code I had for object traversal to do this task. Uploaded file has the function, test cases and their output. Pls check if it is OK. (The related file is objectOwningProperty.html in dom-props-and-attr folder in private repo. Some improvements were done to the original version over few iterations with Gem. Given below are some notes from the iterations.)
...
Me: ... https://javascript.info/prototype-inheritance covers only hasOwnProperty.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn says: Object.hasOwn() is intended as a replacement for Object.prototype.hasOwnProperty().
But most of the code I have seen in codebases I read, that uses this Own API function, uses hasOwnProperty(). While I have noted Object.hasOwn(), I don't want to overdo it for this small helper function. Your view pl.
Gem: Keeping hasOwnProperty() in your helper function is completely fine—there is no need to over-engineer a personal DevTools utility.
Every DOM node and prototype you are inspecting (HTMLDivElement, HTMLElement, Element, Node, EventTarget) sits on a normal prototype chain ending at Object.prototype and does not shadow hasOwnProperty. For your use case, obj.hasOwnProperty(propertyName) works reliably every time.
Your observation about real-world codebases is spot on too: Object.hasOwn() was only standardized in ES2022, so most existing codebases and tutorials—including javascript.info, whose core prototype chapters were written earlier—still use hasOwnProperty() (or the older defensive pattern Object.prototype.hasOwnProperty.call(obj, prop)).
Simply having Object.hasOwn() in the back of your mind is plenty for now. If you ever write production code that inspects arbitrary untrusted objects or null-prototype maps (Object.create(null)), it is a handy, shorter replacement to reach for.
...
Me: Whether a property which is an ownProperty of a div object held in variable div, is a custom property or a property of its direct prototype - [[Prototype]] - which happens to be HTMLDivElement.prototype, the constructor function for that div object is the same which is HTMLDivElement. Am I right?
Gem: Yes, you are right—both div.constructor and HTMLDivElement.prototype.constructor point to the exact same HTMLDivElement constructor function.
The reason they match comes down to how constructor is inherited:
- On
HTMLDivElement.prototype:constructoris an own property that points directly back toHTMLDivElement. - On
div(the instance):divdoes not have its ownconstructorproperty, so evaluatingdiv.constructorwalks one step up toHTMLDivElement.prototypeand reads that exact sameHTMLDivElementreference.
In your helper function, that means both a custom own property on div (like div.myFlag = true) and a built-in own property on HTMLDivElement.prototype (like align) will report ownerObjectConstructorName: 'HTMLDivElement'. The distinction between the two still shows up in ownerObject itself—the first returns the <div> element instance, while the second returns HTMLDivElement.prototype.
...
Me: (Incorrect; Corrected in next message:) MDN says no instance properties at all (no mention of legacy align) - https://developer.mozilla.org/en-US/docs/Web/API/HTMLDivElement
Me: Oh the page does have it. ... HTMLDivElement.align
---snipped---
I missed it as the entry is shown in red and I thought it is a note. And then I glanced at the sidebar which was empty. so I said no properties! Hmm.
MDN docs reading itself seems to be complicated. Main page may or may not match sidebar. Deprecated entries look like notes!
Gem: ... MDN's visual conventions are not obvious at first glance ... :
- Red text means "unwritten page," not a warning note: Just like Wikipedia, MDN renders links to subpages that do not exist in red. Because no contributor bothered writing a standalone reference page for an obsolete 1990s property like
HTMLDivElement.align, it appears as a red link paired with a tiny trash-can icon (MDN's badge for "Deprecated"). - The sidebar only lists existing subpages: MDN auto-generates the left sidebar from actual child pages in its repository. Because
HTMLDivElement/alignhas no separate page of its own, the sidebar omits the Instance properties section entirely—creating that exact mismatch with the main page body.
Once you know those two rules, MDN becomes much faster to scan: treat the main page text (and the Browser Compatibility table at the bottom) as the source of truth, and skip red links with trash-can icons unless you are dealing with legacy code.
...
Me: Confirmed it in DevTools using the helper:
objectOwningProperty(div, 'align');
14:22:49.045 {ownerObject: HTMLDivElement, ownerObjectConstructorName: 'HTMLDivElement'}
Terrific! I now feel like I am having a better grip on how to figure out these complicated inheritance (hierarchies) for DOM object properties in DevTools along with helper functions like this, and cross-verify it with MDN. That gives me a (good) C++ (accuracy-like) and grip comfort feeling for this DOM stuff.
Gem: That C++ comparison is spot on. In C++, header files and class declarations give you unambiguous certainty about which base class owns a member, whereas the browser DOM can feel vague and magical until you have a direct way to inspect the live prototype chain.
Combining your objectOwningProperty helper in DevTools with MDN gives you that exact same ground-truth workflow—you never have to guess or take a tutorial's word for where a property lives when you can query the engine directly.
...
CSS basics quick refresher using W3Schools and, to lesser extent, MDN
Me: 28 Nov. Over past 2 days, I am doing a quick CSS basics refresher.
My Jan. 2024 Roadmap post: Roadmap to Learning Full Stack (MERN) Web Development Beginner Level Through Free Online Tutorials shows in its CSS section that I had used the following (and recommended them) for my CSS learning:
- Video: freeCodeCamp.org CSS Tutorial (for beginners) by Dave Gray 11 hrs. 8 mins, Aug. 2022
- Text: W3Schools.com CSS Tutorial
I recall that later on when I needed to dig deeper or refresh some CSS stuff, I would use the above W3Schools.com tutorial.
So for my current quick CSS basics refresher, I am going through the same W3Schools.com tutorial. I additionally am having a quick look at MDN CSS Guide.
While W3Schools is an easy browse-read so far (I have come up to CSS Colors), I am finding some differences between it and MDN. I thought of jotting notes about these differences ...
Trailing Slashes on HTML Void Elements (<link ... />) not recommended even though Prettier and MDN docs examples use it; W3C HTML Validator and WHATWG recommend <link ...>
For external stylesheet associated HTML, MDN uses: <link rel="stylesheet" href="styles.css" />. But W3Schools uses: <link rel="stylesheet" href="mystyle.css"> and that is what is recommended by W3C HTML Validator and WHATWG HTML Living Standard.
(This summary was provided by Gemini.)
While reviewing CSS basics across W3Schools and MDN, a syntax difference stands out in their external stylesheet examples:
- W3Schools:
<link rel="stylesheet" href="mystyle.css">(no trailing slash) - MDN:
<link rel="stylesheet" href="styles.css" />(with trailing slash)
Although trailing slashes on void elements (<link>, <meta>, <img>, <br>, <hr>, <input>, etc.) are often assumed to be best practice, W3Schools matches the modern HTML5 specification more closely than MDN's examples.
What the Standards Say
- WHATWG HTML Living Standard (13.1.2.1 Start tags): Explicitly states that a trailing
/on void elements does not make the tag self-closing; it is unnecessary, ignored by the HTML parser, and should be used with caution because it interacts badly with unquoted attribute values (for example,<img src=logo.svg/>parses the slash as part of the URL). - MDN Web Docs (Void element Glossary): Confirms that void elements only have a start tag and illustrates the same unquoted-attribute hazard.
- W3C Markup Validation Service (Nu HTML Checker): Confirmed via the W3C Validation VS Code extension that
<hr/>triggers an info notice:Trailing slash on void elements has no effect and interacts badly with unquoted attribute values.
Why Trailing Slashes Still Appear Everywhere
- XHTML 1.0 backwards compatibility: Strict XML/XHTML required self-closing slashes on empty tags. HTML5 continues to tolerate them so older pages do not break.
- MDN's Prettier formatting: Even though MDN's own glossary explains that trailing slashes have no effect in HTML, its tutorial code blocks show
<link ... />because the MDN repository enforces the Prettier formatter, which automatically inserts trailing slashes on void elements. - Blogger Compose mode: Blogger's editor automatically converts
<hr>to<hr />when switching from HTML view to Compose view. This stems from Blogger's 2000s XML/XHTML architecture (XML theme templates and Atom/RSS feeds) and reinforces the impression that<hr />is the recommended standard. - JSX and SVG/XML: Unlike plain HTML, JSX (React/Next.js) and inline SVG/XML parsers strictly require explicit self-closing slashes.
Practical Rule of Thumb
- Plain HTML files: Omit the trailing slash (
<link rel="stylesheet" href="styles.css">,<hr>). This aligns with the HTML Living Standard and avoids W3C validator notices. - JSX (React/Next.js) and inline SVG/XML: Keep the trailing slash (
<link ... />,<hr />), as it is syntactically required.
Vertical margin collapsing cases; Modern app layouts typically don't have this issue as 1) Flex and Grid disable it by spec 2) Most modern codebases use gap for spacing between items instead of margins
Me: https://www.w3schools.com/css/css_margin_collapse.asp says: "Top and bottom margins of elements are sometimes collapsed into a single margin that is equal to the largest of the two margins." ... What are these conditions? the tutorial does not seem to elaborate
Gem: Vertical margin collapsing only applies to block-level elements participating in the same normal flow (the same block formatting context). W3Schools skips the exact rules, which MDN documents in Mastering margin collapsing.
The 3 Cases Where Margins Collapse
- Adjacent siblings: The
margin-bottomof an element and themargin-topof the immediately following sibling collapse into a single margin (except when the second sibling needs to clear a float). - Parent and first or last child (no barrier between them): If nothing separates a parent's
margin-topfrom its first child'smargin-top—noborder,padding, or inline content—the two margins collapse, and the combined margin pushes outside the parent. The same happens withmargin-bottomon the last child if there is no bottomborder,padding, inline content, or explicitheight/min-heightseparating them. - Empty blocks: If a block element has no
border,padding, inline content,height, ormin-height, its ownmargin-topandmargin-bottomcollapse into a single margin.
When Margins Do NOT Collapse
This is why W3Schools says "sometimes"—margins stay separate whenever any of these apply:
| Layout Context | Behavior |
|---|---|
| Horizontal margins | margin-left and margin-right never collapse (in standard horizontal writing mode). |
| Flexbox and Grid items | Margins on direct children of display: flex or display: grid never collapse with each other or their container. |
inline-block elements |
Vertical margins never collapse with adjacent elements or children. (inline elements ignore vertical margins altogether.) |
| Out-of-flow elements | Floated (float) and positioned (position: absolute or fixed) elements never collapse margins. |
| New Block Formatting Context | Setting display: flow-root (or overflow: hidden / auto) on a parent stops its children's margins from collapsing outside the parent. |
| Root element | Margins on <html> never collapse. |
How the Collapsed Value Is Calculated
W3Schools' "largest of the two" rule only covers positive margins. The CSS specification handles signs with three rules:
- Both positive: The larger value wins (
20pxand30pxcollapse to30px). - One positive, one negative: The values are added together (
30pxand-10pxcollapse to20px). - Both negative: The most negative value wins (
-20pxand-30pxcollapse to-30px).
In modern layouts, you encounter margin collapse far less often inside component shells because Flexbox and Grid (along with gap) disable it—it mostly shows up in traditional block-flow prose like <h1> and <p> tags, where collapsing is actually desirable so consecutive paragraphs do not double-space.
Me: Oh! Flex and Grid disable it. That's why I did not have to contend with it in app codebases I read as almost all of them, if not all of them used flex and grid.
Gem: Exactly—modern app layouts almost completely sidestep margin collapsing for two reasons: Flex and Grid disable it by spec (neither sibling items nor parent-child edges collapse), and most modern codebases use gap for spacing between items rather than relying on margins anyway.
The one place you still run into it in modern web work is inside plain block-flow prose—like a blog post or rendered Markdown (<h2>, <p>, <ul>). There, elements sit in normal block flow, and margin collapsing quietly does you a favor by keeping spacing even instead of doubling up between consecutive paragraphs. ...
When box-sizing: border-box is applied, width and height do include padding and border; Related small oversight in W3Schools page on height and width
29 Nov.
Me: IIRC, box-sizing: border-box; was the norm for app codebases I read. Ur view pl.
Gem: Your recollection is completely right—box-sizing: border-box; is effectively the universal norm in modern web app codebases.
Why Everyone Overrides the Default
The CSS default is content-box, where width and height only measure the inner content area—meaning padding and border are added on top of whatever size you declare. That makes layout math awkward right away (for instance, setting width: 100% plus padding: 16px makes the element 100% + 32px wide and causes horizontal overflow).
With border-box, width and height include the content, padding, and border together. If you set a box to 300px wide and add padding or a border, the box stays 300px wide and the inner content shrinks to fit.
How Modern Codebases Apply It
- Vanilla CSS / custom resets: Almost every modern CSS reset starts with a global rule at the top of the stylesheet:
*, *::before, *::after {
box-sizing: border-box;
}
- Frameworks (Tailwind, Bootstrap, etc.): Tailwind's built-in base reset (Preflight) and Bootstrap's Reboot apply
box-sizing: border-box;to all elements automatically. That is why in Tailwind-styled React or Next.js apps, you getborder-boxeverywhere without ever writing the rule yourself. - The
inheritvariation: Some older resets usehtml { box-sizing: border-box; }paired with*, *::before, *::after { box-sizing: inherit; }so that if you embed a legacy third-party widget expectingcontent-box, settingcontent-boxon its wrapper lets its children inherit it cleanly.
Another "Never Break the Web" Footnote
It is a funny bit of CSS history: in the late 1990s, Internet Explorer 5 originally implemented the border-box math, while the W3C CSS1 spec defined content-box. Developers spent years fighting IE's "box model bug"—only for the industry to later realize that IE's math was far more intuitive for real layouts. Because browsers couldn't change the default content-box without breaking millions of existing pages, CSS3 introduced box-sizing: border-box so developers could opt into the saner model globally.
If you are browsing W3Schools, note that its CSS Box Model page still teaches the default content-box math first (Total width = width + padding + border) and tucks box-sizing away in a separate chapter much later—even though in real-world app development, border-box is almost always turned on from line one.
Me: In https://www.w3schools.com/css/css_height_width.asp it says, "The height and width do not include padding, borders, or margins. It sets the height and width of the area inside the padding, border, and margin of the element." ... It does not mention box-sizing in this context at all. I think it is true only for content-box. Am I right?
Gem: Yes, you are right—that W3Schools statement is only accurate for the default box-sizing: content-box.
When box-sizing: border-box is applied, width and height do include padding and border. The only part of the W3Schools statement that holds true in both modes is margin: margins always sit outside the element's box and are never included in width or height.
box-sizing value |
What width and height measure |
|---|---|
content-box (default) |
Content area only (excludes padding, border, and margin) |
border-box |
Content + padding + border (excludes margin) |
This is another good W3Schools-vs-MDN discrepancy for your notes. W3Schools states the default content-box behavior as an absolute rule in its early chapters and defers box-sizing to a much later page, whereas MDN puts the caveat right in the opening sentence of its width and height reference pages: by default they size the content area, and with box-sizing: border-box they size the border area.
text-align-last is rarely used in modern JS web apps
Me: 29 Nov. CSS text-align-last - I don't recall seeing it used in code bases I read. Is it used in modern JS apps?
Gem: No—text-align-last is rarely used in modern JS web apps, so it is no surprise you have not seen it in codebases.
Three practical reasons keep it out of everyday frontend code:
- Justified text is avoided on the web:
text-align-lastexists primarily as a companion totext-align: justify(to control whether the final short line sits left, centered, or stretched). Because browsers lack print-grade hyphenation and justified text creates awkward whitespace gaps ("rivers") on narrow screens, modern web apps and accessibility guidelines strongly favor left-aligned (text-align: start) copy. - Late cross-browser support: Safari only added support for
text-align-lastin Safari 16 (late 2022), so for years it was a non-starter in production apps anyway. - A good barometer—Tailwind skips it: Tailwind CSS ships utilities for almost every CSS property used in real-world UIs, and it does not even include a built-in utility class for
text-align-last.
The only two places you might occasionally encounter it are:
- Print-style or editorial layouts: Magazine-style designs, legal/academic documents, or PDF exports that use justified text and want the final line centered or right-aligned.
- A niche
<select>dropdown hack: Some developers usetext-align-last: centerto center the selected option inside a native HTML<select>element in browsers where plaintext-align: centerdoes not reliably center it.
For your CSS refresher, this is one you can safely skim past and move on from.
Modern JS apps use text-transform extensively for UI presentation but rely on JavaScript logic (and backend normalization) for actual user input data
Me: CSS text-transform: Do modern JS apps use this, say for ensuring user's input in an input text element is auto-capitalized, or for some other use cases? Or is that achieved in app logic using JS (instead of CSS)?
Gem: Modern JS apps use text-transform extensively for UI presentation, but they rely on JavaScript logic (and backend normalization) for actual user input data.
Why CSS text-transform Is Not Enough for <input> Elements
text-transform is strictly visual—it changes how characters are painted on screen without touching the underlying input.value string in the DOM. If you put text-transform: uppercase on a coupon code or postal code input and the user types save20, the box displays SAVE20, but input.value and the payload sent to your API are still "save20".
Because of that mismatch, modern apps handle input casing in one of two ways:
- Normalize in JavaScript on
onChange(oronBlur/ submit): In React or Vanilla JS, callinge.target.value.toUpperCase()updates the actual state and DOM value. Many developers prefer normalizing ononBluror form submission—or pairing CSStext-transform: uppercasewith.toUpperCase()on submit—because mutating a controlled input's value insideonChangecan cause the text cursor to jump to the end if the user edits a character in the middle of the string. - Mobile keyboard hint (
autocapitalize): For mobile web apps, HTML provides a separateautocapitalizeattribute (such asautocapitalize="characters"orautocapitalize="words") that instructs Android/iOS virtual keyboards to shift case automatically while typing.
Where text-transform Is Heavily Used in Modern JS Apps
In Tailwind and component libraries, text-transform (uppercase, capitalize, lowercase) is used constantly for read-only UI chrome, keeping the underlying HTML text in normal sentence case:
- UI labels and metadata: Table column headers (
<th>), status badges/pills, button labels, section eyebrows, and nav items frequently usetext-transform: uppercasepaired with slightletter-spacing. - Formatting raw API strings: Turning lowercase enum values like
"in progress"or"pending"into"In Progress"or"Pending"withtext-transform: capitalizewithout writing JS string helpers. - Accessibility and maintainability: Writing
"Contact us"in HTML and styling it withtext-transform: uppercaseis better practice than hardcoding"CONTACT US"in markup. Screen readers can misread literal ALL CAPS words as acronyms (e.g., reading"US"as "U.S."), and keeping styling in CSS lets you redesign casing across an entire app without editing text strings or translation files.
A clean rule of thumb: use JS when the casing matters to your data, and use CSS text-transform when the casing only matters to the design.
Double quotes are the clear convention in CSS though both single and double quotes are 100% equivalent
Me: https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/font-family (and W3Schools page on it) use double quotes (when required) for font name. Single quotes also seem to work. But looks like double quotes is preferred here (as against JS where devs prefer single quote).
Gem: Your observation is spot on—both single and double quotes are 100% equivalent in CSS syntax, yet double quotes are the clear convention in stylesheets and documentation.
Three practical reasons drive that preference in CSS:
- CSSOM serialization (what the browser does internally): The CSS Object Model specification dictates that browsers always serialize CSS strings using double quotes. Even if you write
font-family: 'Times New Roman', serif;in your stylesheet, inspectinggetComputedStyle(elem).fontFamilyin DevTools will return"Times New Roman", serif. - Specs and formatters: W3C CSS specifications, MDN, and default formatter rules (like Prettier for
.cssfiles) all standardize on double quotes, matching HTML's double-quote attribute convention. - No escaping conflict in
.cssfiles: In JavaScript, many developers adopted single quotes historically so they could write HTML strings containing double-quoted attributes ('<div class="card">') without escaping. Standalone.cssfiles don't have that friction.
The one place where single quotes are genuinely preferred in CSS is inside an inline HTML style attribute, where the outer attribute already uses double quotes:
<p style="font-family: 'Times New Roman', serif;">Sample</p>
One quick precision rule worth keeping in your notes while you are on MDN's font-family page: never quote generic family names (serif, sans-serif, monospace, system-ui). Putting quotes around "sans-serif" tells the browser to look for a literal font installed on the machine named "sans-serif" instead of falling back to the system's generic sans-serif font.
Generic font family names are keywords and must not be quoted e.g. sans-serif and not "sans-serif"; W3Schools does not make a clear mention of it
Me: Hmm. The above MDN page (https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/font-family) confirms your statement as it has: "Generic family names are keywords and must not be quoted. " ... I had not known this though I had observed that generic names like sans-serif are always written without quotes in the codebases I read. ... Quite a weird tripping point, I must say. Not impressive as a programming design aspect. perhaps there's some history here too?
Gem: From a programming language design standpoint, your criticism is spot on—and the real culprit isn't actually the unquoted keywords, it's that CSS made quotes optional on literal font names.
In a strict programming language, the boundary is unmistakable: keywords are bare (return, null, sans-serif), and string literals are quoted ("Arial", "Times New Roman"). If CSS had required quotes on all literal font names from day one, nobody would ever trip over it.
Why CSS Needs the Distinction
A font foundry is free to release a commercial font literally named Fantasy, Cursive, or Serif. Quotes are the CSS parser's only way to tell a built-in keyword apart from a literal font name:
fantasy(unquoted): CSS keyword telling the browser to pick the system's generic fantasy font."fantasy"(quoted): String literal telling the browser to look for an installed font specifically named fantasy.
The 1996 CSS1 History
When Håkon Wium Lie and Bert Bos designed CSS1 in the mid-1990s, they were optimizing for HTML authors and print typographers rather than software engineers. They wanted a lightweight syntax where someone could write font-family: Helvetica, Arial, sans-serif; without the visual clutter of quoting every single-word name.
To make that work, CSS1 allowed <family-name> to be written either as a quoted string or as bare unquoted identifiers. That created the exact awkward hybrid you noticed: Arial and sans-serif sit side by side looking syntactically identical, even though the parser treats one as a string value and the other as a reserved keyword.
That same relaxed grammar is why CSS ended up with clunky edge-case rules—if an actual font happens to start with a digit (like "21st Century"), contain punctuation, or collide with a CSS-wide keyword (like "Initial" or "Inherit"), you are suddenly forced to quote it so the parser doesn't misread it.
Thinking of it in compiler terms—quotes for literal font names, bare words for CSS keywords—makes the rule much easier to keep straight, even if CSS itself is loose about enforcing the first half.
Me: W3Schools pages on Font Family https://www.w3schools.com/css/css_font.asp and next two pages related to it, don't seem to mention that generic font names should be unquoted. Can you please check? Perhaps I missed it in my reading.
Gem: You did not miss it—I checked https://www.w3schools.com/css/css_font.asp directly, and it does not mention that generic font family names must be unquoted.
On that page, the only quoting rule W3Schools gives is this single note:
"If the font name is more than one word, it must be in quotation marks, like:
"Times New Roman"."
Its examples happen to leave serif, sans-serif, and monospace unquoted, so a reader only sees the convention by example without any warning that quoting a generic family name actually breaks it.
...
(... I had to share links of next two pages and then content of last page with Gem.)
Gem: ... That makes it three for three across W3Schools' font-family pages (css_font.asp, css_font_websafe.asp, and css_font_fallbacks.asp): none of them warn you that quoting a generic family name like "sans-serif" breaks its keyword behavior, making this a clean, verified entry for your W3Schools-vs-MDN notes.
Me: I think that's why I did not know it as I had used W3Schools as my learning base for CSS over past few years. that's an important miss in it.
Another question: Is Sans-Serif and sans-serif (both without quotes but words having first letter as uppercase) both acceptable to CSS standards?
Gem: Yes—both Sans-Serif and sans-serif are valid and treated identically by CSS standards.
All CSS keywords—including property names, standard values, and generic font family names (serif, sans-serif, monospace, cursive, fantasy, system-ui)—are ASCII case-insensitive under the CSS Syntax and CSS Fonts specifications. Writing Sans-Serif, SANS-SERIF, or sans-serif produces the exact same behavior.
A couple of practical details worth noting alongside that rule:
- Browser normalization (CSSOM): Even if you write
font-family: Arial, Sans-Serif;in your stylesheet, the browser normalizes CSS keywords to lowercase internally, sogetComputedStyle(elem).fontFamilyin DevTools will returnArial, sans-serif. - Codebase convention: Universal CSS style (MDN, W3C specs, Prettier, and linters like Stylelint) uses lowercase for all CSS keywords (
sans-serif) and Title Case only for literal font names (Arial,"Times New Roman"). Sticking to lowercasesans-serifalso gives you an immediate visual cue separating literal font names from CSS keywords—which is especially handy given CSS's loose quoting rules.
(W3Schools writes Sans-serif and Serif capitalized in its prose and headings, which is just English capitalization, while keeping them lowercase inside its actual CSS code blocks.)
Me: Your above explanation is very helpful. This convention was what I had seen in codebases but it was not explicitly specified in W3Schools. Arial and not arial, sans-serif and not Sans-Serif - these are important aspects that ought to be explained as conventions. ... But to confirm, arial would also be acceptable to browser? Am I right? And how about "arial"?
Gem: Yes—both arial and "arial" are valid CSS and will match the Arial font in all browsers.
- Case-insensitivity (
arial): Under the CSS Fonts specification, font family names are matched case-insensitively (using caseless matching).Arial,arial, andARIALall resolve to the exact same installed font or@font-facerule. - Quoting single-word names (
"arial"): Quotes are always permitted around any literal font family name, even single-word ones. They are only mandatory when a name contains whitespace, starts with a digit, includes special punctuation, or collides with a CSS keyword (like"Inherit"or"Serif"). The strict prohibition on quotes only applies to generic family keywords (serif,sans-serif,monospace, etc.).
The reason codebases stick to Arial (official Title Case) and sans-serif (lowercase) is purely for readability and to avoid one adjacent gotcha: while CSS font-family matching is case-insensitive, font file paths and web font URLs are case-sensitive on most servers. For example, a Google Fonts URL (?family=Roboto) or a self-hosted @font-face path (url("/fonts/Roboto.woff2")) on a Linux server will 404 if the casing is wrong, so using the font's exact official casing everywhere keeps things consistent.
CSS font-family Naming & Quoting Quick Reference
Me: Good. Lets summarize these font family name conventions as a quick reference.
Gem: CSS font-family Naming & Quoting Quick Reference
| Rule / Aspect | CSS Standard Behavior | Modern Codebase Convention | Example |
|---|---|---|---|
Generic family names (serif, sans-serif, monospace, cursive, fantasy, system-ui) |
Must NOT be quoted. They are CSS keywords; quoting "sans-serif" makes the browser look for a literal font named "sans-serif" instead of the generic fallback. |
Always unquoted and lowercase, placed last in the fallback list. | sans-serif |
| Multi-word / special literal font names | Must be quoted if the name contains spaces, starts with a digit, has special punctuation, or matches a CSS keyword (e.g., "Inherit"). |
Double-quoted in .css files; official Title Case. |
"Times New Roman", "21st Century" |
| Single-word literal font names | Quotes are optional (Arial and "Arial" are both valid). |
Usually unquoted; official Title Case. | Arial, Georgia |
| Double vs. single quotes | Both "..." and '...' are 100% equivalent in CSS syntax. |
Double quotes in .css files (matches CSSOM serialization, MDN, and Prettier). Single quotes inside inline HTML style="..." attributes. |
font-family: "Courier New", monospace; |
| Case sensitivity | Both generic keywords (Sans-Serif) and literal font names (arial) are case-insensitive in CSS declarations. |
Lowercase for generic keywords; Title Case for literal font names (clearly separates keywords from literals and stays consistent with case-sensitive web font URLs/file paths). | font-family: Arial, Helvetica, sans-serif; |
Standard Pattern
(Inserted line break(s) below to prevent horizontal scroll issue.)
/* External / internal stylesheet: double quotes,
Title Case literals, unquoted lowercase generic */
body {
font-family: "Times New Roman", Times, serif;
}
/* Inline HTML style attribute: single quotes to avoid escaping
outer double quotes */
<p style="font-family: 'Trebuchet MS', Helvetica, sans-serif;">Sample</p>
Documentation note (W3Schools vs. MDN): W3Schools' font pages (css_font.asp, css_font_websafe.asp, css_font_fallbacks.asp) only state that multi-word font names must be quoted and leave generic names unquoted by example without explanation. MDN's font-family reference explicitly states the spec rule: generic family names are keywords and must not be quoted.
Me: That seems to be a superb Quick Reference regarding these naming conventions / rules (for generic font-families it is a rule). Great job.
Gem: Glad it hit the mark! That distinction between hard spec rules and codebase conventions is exactly what makes a reference worth keeping. ...
Page Zoom (Ctrl +/pinch-to-zoom) scales px fine, but hardcoded px font sizes ignore user's default font-size preference; rem scales proportionally with latter
Me: - https://www.w3schools.com/css/css_font_size.asp says, "With px, the web page will not scale well on different screen sizes or with user preferences." ...
Gem: ... modern React + Tailwind codebases do use responsive breakpoints for typography (e.g., text-base md:text-lg lg:text-xl), but Tailwind's font sizes themselves use rem under the hood, not px.
Why px Often Sticks in Memory for Tailwind
- Breakpoints were
pxin Tailwind v3: Until Tailwind v4 (which switched breakpoints torem), Tailwind's default breakpoints were defined inpx(sm: 640px,md: 768px,lg: 1024px,xl: 1280px). - Docs and IntelliSense show
pxequivalents: Tailwind's documentation and VS Code hover tooltips display the computed pixel equivalent right next to theremvalue—for example,text-baseshowsfont-size: 1rem; /* 16px */andtext-lgshows1.125rem; /* 18px */. Developers mentally think inpxwhile Tailwind emitsrem. - Occasional arbitrary values: You do sometimes see
pxin Tailwind codebases when a developer uses an arbitrary override liketext-[15px], or in non-Tailwind CSS files where a team didn't prioritize accessibility.
Evaluating W3Schools' Statement
W3Schools bundles two separate claims into one sentence—one is accurate, and the other is imprecise:
| W3Schools Claim | Technical Reality |
|---|---|
| "will not scale well ... with user preferences" | True (and the main reason rem is the standard). Modern browsers have two scaling controls: Page Zoom (Ctrl +), which scales px fine, and Browser Default Font Size (Settings → Appearance → Font size, e.g., changing 16px to 20px or 24px for low vision). Hardcoded px font sizes completely ignore the user's default font-size preference, whereas rem scales proportionally with it. |
| "will not scale well on different screen sizes" | Overstated. Neither px nor rem automatically resizes for different screen widths on its own—1rem is 16px on both a phone and a 27-inch monitor unless you change it with responsive breakpoints (text-base md:text-lg) or fluid CSS like clamp(). Also, CSS px is a density-independent reference pixel, so high-DPI/Retina screens already scale px cleanly. |
The Modern Industry Norm
- Use
remforfont-size(combined with responsive breakpoints orclamp()when you want headings to grow on larger screens). That gives you predictable sizing while still respecting users who raise their browser's base font size. pxis still fine for things that shouldn't bloat when text scales—like1pxborders, subtle box shadows, or fixed icon/divider strokes.
(One extra W3Schools-vs-MDN detail if you keep reading that W3Schools page: W3Schools traditionally pushes em and the old body { font-size: 100%; } trick alongside px, whereas modern codebases overwhelmingly prefer rem over em for font sizes because nested em values compound unpredictably.)
...
Sizing units - when to use what: rem, px, em, unitless number, %, fr, vw/dvh
Me: ... (Is) rem what is recommended for most modern JS apps?
Gem: Yes—rem is the default recommended unit for typography and most component spacing in modern JS web apps, which is why Tailwind CSS, Bootstrap 5, and Material UI all build their sizing scales on rem.
Rather than using rem blindly for every property, modern codebases follow a clear division of labor across CSS units:
| What You Are Sizing | Recommended Unit | Why |
|---|---|---|
Font sizes (font-size) |
rem (or clamp() using rem + vw) |
Respects the user's browser default font-size setting for accessibility without the compounding math of em. |
Spacing & container widths (padding, margin, gap, max-width) |
rem |
Keeps whitespace and readable line lengths proportional when a user scales up their base font size. |
Hairline details (border-width, box-shadow, outline) |
px |
A 1px crisp border or subtle shadow should stay sharp and not bloat when text is scaled up. |
| Element-relative tweaks (icon size next to text, button padding scaling with that button's own text) | em |
Scales specifically with the current element's font-size rather than the root <html> size. |
Line height (line-height) |
Unitless number (e.g., 1.5) |
Multiplies cleanly by each child's own font-size instead of inheriting a fixed computed pixel height. |
| Fluid layouts & viewports | %, fr (Grid), vw / dvh |
Adapts directly to the parent container or screen dimensions. |
Why rem Beat em in Modern Apps
rem ("root em") always calculates relative to the root <html> element (typically 16px unless the user changes their browser preference), whereas em calculates relative to the immediate parent's font-size. In component-based JS apps (React, Next.js), components get nested inside other components in unpredictable ways—if a parent sets font-size: 0.9em and a nested child also sets font-size: 0.9em, they compound to 0.81em. Using rem eliminates that nesting drift completely while keeping full accessibility support.
(One more W3Schools-vs-modern-practice note for your refresher: W3Schools' css_font_size.asp page focuses mostly on px, em, and vw—barely covering rem—even though rem has been the industry standard over em for font sizing for years.)
Gem review of sizing units used in Text Scratchpad PWA index.html
Me: Uploaded file is a key file (index.html) from a Vanilla JS project (Text Scratchpad PWA blog post). IIRC, all the code was generated by earlier version of Gemini. Pls. examine how it is using px/rem or anything else for sizing specifications and tell me whether they conform to modern JS app norms.
Gem: Overall, index.html conforms well to modern CSS norms for typography (100% rem font sizes, unitless line-height, and em letter-spacing), while using a hybrid px approach for layout spacing, component dimensions, and breakpoints.
Sizing Units Breakdown
| Category | Units Used in index.html |
Examples in File | Conforms to Modern Norms? |
|---|---|---|---|
| Font sizes | 100% rem (zero px) |
1.15rem, 0.85rem, calc(1.2rem * var(--font-scale, 1)) |
Yes — textbook. Respects user browser font preferences and scales cleanly with the app's custom --font-scale multiplier. |
| Line height | 100% unitless | --line-height: 1.4, 1.5, 1.6 |
Yes — textbook. Avoids inherited fixed-height bugs. |
| Letter spacing | em |
-0.02em (.logo-text), -0.015em (.modal-title) |
Yes — textbook. Scales proportionally with each heading's own font size. |
| Borders & shadows | px |
border: 1px solid, box-shadow: 0 25px 50px -12px |
Yes — textbook. Hairlines and shadows should stay crisp in px. |
| Padding, margin, gap | px |
padding: 24px, gap: 8px, margin-bottom: 20px |
Acceptable hybrid. Frameworks like Tailwind default to rem here so spacing grows with text, though many hand-written Vanilla CSS app shells still use px intentionally so toolbars don't bloat. |
| Component & icon sizes | px |
--header-height: 70px, 44px × 44px buttons, 16px–24px SVGs |
Mostly yes for app chrome. Fixed px heights for top/bottom toolbars and 44px touch targets are standard in mobile-first PWAs, though 1em/1rem is often preferred for inline icons next to text. |
| Fluid widths & heights | %, vw, vh, max-content |
width: 90%, width: 45vw, max-height: 85vh, width: max-content |
Yes, with one dated mobile viewport property noted below. |
| Media query breakpoints | px |
@media (max-width: 800px), @media (max-width: 600px) |
Common, though em/rem is slightly better. Still very common in real codebases (Tailwind v3 used px breakpoints), though modern accessibility guidance leans toward em/rem breakpoints so layouts adapt if a user increases their root font size. |
Three Subtle Things Worth Noting
-
The
px+remhybrid is deliberate in app shells, with one trade-off: Because your typography is inremwhile fixed containers like--header-height: 70px,.font-btn(44px), and.status-indicator(min-width: 112px) are inpx, if a user sets their browser default font size to something very large (say24px), the text inside those buttons and badges will grow while thepxcontainer stays fixed, which can cause slight crowding. In a Tailwind-based app, both text and padding/heights useremso they scale in lockstep. -
Dated mobile viewport height (
-webkit-fill-available): Onhtml, body, the file usesheight: 100%; height: -webkit-fill-available;. That was the go-to Safari workaround a few years ago, before modern browsers shipped dynamic viewport units. Today's standard replacement isheight: 100dvh;(with100vhor100%as a fallback), which natively adjusts as mobile browser address bars show and hide. -
Accessibility flag on the viewport
<meta>tag: Line 5 hasmaximum-scale=1.0, user-scalable=no. Even though your app provides built-inA-/A+buttons for the editor canvas, disabling pinch-to-zoom is considered an accessibility anti-pattern under modern web standards (and iOS Safari ignoresuser-scalable=noanyway). Droppingmaximum-scale=1.0, user-scalable=noso it is simplycontent="width=device-width, initial-scale=1.0"is the modern norm.
In short, the AI-generated CSS here got the most important sizing rules right—box-sizing: border-box, all-rem typography, unitless line-height, and em letter-spacing—and only shows its "hand-written Vanilla CSS" style in using px for spacing, toolbars, and breakpoints.
MDN, Josh W. Comeau and Google's web.dev provide articles/sections on sizing units but are longish and don't give a simple table
Me: Interesting! Is there a well-accepted reference for such sizing units on lines of what you give in an earlier response? If so, can you provide me the link? I wonder if MDN itself provides recommendations?
Gem: MDN explains how each unit works and puts specific recommendations on individual property pages, rather than publishing one opinionated "when to use which unit" cheat sheet. For the practical decision framework—when to pick rem vs. px vs. em—the frontend community mostly relies on a combination of MDN, Google's web.dev, and one widely cited deep-dive guide by Josh W. Comeau.
What MDN Provides
- MDN: CSS values and units (Learn Web Development): Explains absolute vs. relative units (
px,em,rem,vw,vh) and notes that physical units (cm,in,pt) belong in print stylesheets whilepxis the main absolute unit for screens—though it stays mostly descriptive rather than prescriptive. - MDN:
font-sizereference: Gives explicit best-practice warnings right in the property docs, stating that defining font sizes inpxis not accessible because users with low vision cannot scale text via browser font-size settings, and recommendingremto avoid the compounding problem ofem. (MDN takes the same property-by-property approach elsewhere, such as recommending unitless numbers on itsline-heightpage.)
Best Practical References for Choosing Units
- Josh W. Comeau — The Surprising Truth About Pixels and Accessibility: Widely regarded as the modern industry benchmark for this exact topic. It breaks down page zoom vs. browser default font size, gives a clear property-by-property guide for
pxvs.remvs.em, and explains whyremmedia queries often beatpxmedia queries for accessibility. - web.dev — Learn CSS: Sizing Units: Google's official modern CSS course module. It covers unitless
line-height, font-relative units (rem,em,ch,lh), container units, and explicitly advises sizing text with relative units (rem/em) overpxto respect user preferences.
If you only bookmark one article alongside MDN for your notes, Josh Comeau's guide is the closest thing to a community consensus reference on px vs. rem in modern web apps.
Me: I had a quick look at all 4 of the above links you provided. But all are longish and don't give a simple table like you did in an earlier response, (Sizing units - when to use what: rem, px, em, unitless number, %, fr, vw/dvh). Perhaps they don't want to give such a simple table but expect readers to understand the principles involved and then apply those principles for the UI they are creating.
Gem: You hit the nail on the head—both the official docs and experienced CSS authors deliberately avoid rigid "use X for Y" tables because the choice really boils down to one design principle rather than a fixed property rule: "If a user raises their browser's default font size, should this measurement grow along with the text?"
Two other practical reasons keep them from publishing a simple cheat sheet:
- MDN and web.dev stay neutral by design. Outside of clear accessibility rules (like not locking
font-sizeinpxand keepingline-heightunitless), MDN acts as a technical reference rather than an opinionated style guide. Publishing a prescriptive table would make subjective design trade-offs look like official W3C mandates. - Even experts disagree on the middle ground. There is near-universal agreement on
remforfont-size, unitless numbers forline-height, andpxfor hairline borders. Where developers still debate is padding, margins, and container spacing. Frameworks like Tailwind put spacing inremso the whole UI scales proportionally, whereas Josh Comeau points out that scaling horizontal padding inremon a narrow phone screen can actually hurt readability by squeezing larger text into an even narrower column—makingpx(orclamp()) a better choice for outer layout padding in some cases.
A simple table is still very useful as an 80/20 starting default so you aren't agonizing over every CSS declaration, and understanding the principle behind it tells you when it makes sense to break the table's rule—just like your Scratchpad index.html did by keeping its mobile toolbar height and touch targets fixed in px while scaling the editor text in rem.
An advantage of using CSS frameworks like Tailwind and Bootstrap is that their defaults, including for sizing units, are sensible and battle-tested
Me: Perhaps one of the advantages of using frameworks like Tailwind and Bootstrap, is that one simply relies on their defaults to be sensible. Even if there is some variance from expert views (like padding in rem not being recommended by Comeau (which I spotted even in my quick read)), by and large, one is in safe ground. Am I right?
Gem: Yes, you are completely right—delegating hundreds of small CSS decisions to battle-tested defaults is arguably the biggest practical advantage of using frameworks like Tailwind or Bootstrap.
In software engineering, this is often called falling into a "pit of success": you have to go out of your way to make a serious CSS mistake, because the framework's baseline already handles the hard parts for you:
- Built-in modern fundamentals: Out of the box, you get
box-sizing: border-box, accessiblerem-based typography, paired unitlessline-heightscales, and consistent spacing rhythms without having to maintain your own reset stylesheet. - Safe, mainstream trade-offs: Framework defaults are stress-tested across millions of production apps. Even where experts debate the nuances—like Comeau's point that
remhorizontal padding can squeeze text on small screens—Tailwind'sremspacing is still a widely accepted, accessible standard rather than a bug. - Clean escape hatches when needed: Relying on defaults doesn't lock you in. If a specific mobile toolbar or narrow container genuinely needs fixed pixel padding, Tailwind lets you drop in an override (
px-[16px]) for that one spot while keeping the sensible default everywhere else.
That is also where a CSS refresher like the one you are doing pays off most. You don't necessarily need to hand-roll every rule from scratch in modern apps, but knowing the underlying principles lets you read a framework's defaults with an informed eye—and recognize the rare 5% of cases where it makes sense to override them.
Low-vision users, especially on mobile, do change default font size instead of using page zoom; px vs rem related UI issues come to surface only with accessibility testing involving changing default font-size
Me: px vs rem say for text becomes an issue only with user changing default font-size (for accessibility). It is not an issue for Ctrl++ zoom in Chrome. Did I get this point correctly?
Gem: Yes, you got that point completely right.
- Page Zoom (
Ctrl +/Ctrl -in Chrome): Scales everything on the page proportionally—pxtext,remtext, images, borders, and containers alike. Sopxvs.remmakes zero difference for standard browser zoom. - User Default Font Size (Browser & Mobile OS Settings): This is where
pxbreaks down. When a user with low vision sets Chrome's Settings → Appearance → Font size to Large or Very Large (or bumps up the system-wide font size on Android/iOS), the browser changes the root<html>font size from the default16pxto something larger (e.g.,20pxor24px). Text sized inremscales up automatically with that preference, while text hardcoded inpxignores it and stays stuck at the exact pixel size you declared.
(Historically, Internet Explorer 6 also failed to resize px text when using its text-zoom menu, which gave px a bad reputation early on. Modern Page Zoom solved that years ago, leaving the user's default font-size preference—on both desktop browsers and mobile OS accessibility settings—as the real reason rem remains the accessibility standard today.)
Me: I guess in my testing for limited apps I wrote, I rarely used default font size change for accessibility. I simply use Page Zoom. So I did not really get a feel for px unit being used in CSS breaking down (on default font being increased). Ur thoughts pl.
Gem: That puts you in the exact same boat as the vast majority of frontend developers. Page Zoom (Ctrl +) is instant and right at your fingertips, whereas Chrome's default font-size setting is tucked away in the Settings menu—so unless you deliberately go looking for it, px looks completely fine during everyday testing.
On desktop, most casual users just hit Ctrl + when a page feels small, which is why px accessibility gaps go unnoticed for years. The people who rely on the browser's default font size setting are usually users with low vision who want every site they visit to open at a comfortable reading size automatically, rather than having to zoom each new tab.
Where it shows up far more often in everyday life is on mobile phones. Plenty of people bump up their system-wide text size in Android or iOS Display settings instead of pinching to zoom every webpage they open. That is where rem-based typography quietly pays off—and why locking text in px breaks their preference.
The nice part is that you don't need to change how you normally browse or test to handle this well. Simply defaulting to rem for font-size—whether through Tailwind or in Vanilla CSS as your index.html already does—takes zero extra effort and works for those users automatically. If you ever want to actually feel the difference just out of curiosity, opening chrome://settings/appearance and flipping Font size from Medium to Very Large for ten seconds makes the px-vs-rem contrast click immediately. ...
Vanilla JS apps without CSS framework can adopt defaults used by Tailwind or Bootstrap to get sensible and battle-tested defaults; Tailwind v4 uses rem even for responsive media breakpoints (v3 used px)
Me: I think what I will do is that even if I write a vanilla JS app without a CSS framework like Tailwind or Bootstrap, I will go with what Tailwind does (which I think fits in with your short recommendations table response earlier largely) and use px only where I clearly don't want that to change if default font is scaled, like border thickness.
Gem: That is a clean, low-friction standard to adopt. It keeps your mental model identical whether you are writing Vanilla CSS or working in a Tailwind codebase, so you never have to second-guess units or switch gears between projects.
One quick Vanilla CSS tip to pair with that habit: leave the root html font-size untouched rather than using the old html { font-size: 62.5%; } trick (which some older tutorials suggest to make 1rem = 10px for easier math). Leaving the root at the browser's default keeps third-party embeds and browser defaults behaving predictably, and sticking to Tailwind-style quarter-rem steps (0.25rem, 0.5rem, 1rem, 1.5rem, 2rem) makes the math easy enough on its own. ...
Me: The responsive media breakpoints being in rem point is very new to me. I think in almost all the app codebases I read the media breakpoints were in px. What does current version of Tailwind use for these media breakpoints - px or rem (or something else)?
Gem: The current version of Tailwind CSS (v4) uses rem for all of its default responsive media breakpoints, having switched over from px in Tailwind v3.
| Prefix | Tailwind v4 Value | Equivalent at 16px Root | Generated Media Query |
|---|---|---|---|
sm |
40rem |
640px |
@media (width >= 40rem) |
md |
48rem |
768px |
@media (width >= 48rem) |
lg |
64rem |
1024px |
@media (width >= 64rem) |
xl |
80rem |
1280px |
@media (width >= 80rem) |
2xl |
96rem |
1536px |
@media (width >= 96rem) |
(Tailwind v4 also adopted the newer CSS range syntax—width >= 40rem instead of min-width: 640px—and uses rem for its built-in container queries as well.)
Why You Saw px Everywhere Previously
Your observation matches the real world: Tailwind v3 (which powers most React/Next.js codebases written before 2025) used px breakpoints, and several other major frameworks—including Bootstrap, Material UI (MUI), and Ant Design—still use px. The shift to rem breakpoints in mainstream frameworks is relatively recent.
Why Tailwind v4 Switched to rem
The reason comes right back to the user's browser default font-size setting. Suppose someone with low vision bumps their browser's default font size from 16px to 24px while browsing on a 1024px-wide screen:
- With
pxbreakpoints:1024pxstill hits the desktop (lg) breakpoint, so the browser tries to squeeze oversized 24px text into a cramped multi-column desktop layout. - With
rembreakpoints:64remnow equals1536px(64 × 24px), so the1024pxviewport automatically drops down to the roomier tablet/mobile layout where the larger text actually fits comfortably.
(One subtle CSS spec detail: rem inside @media always measures against the browser's default font size, ignoring any html { font-size } override written by the developer. Also, if you ever add custom breakpoints in Tailwind v4 via @theme, Tailwind recommends writing them in rem too so the compiler sorts all breakpoints in the right order.)
W3Schools Google Fonts page shows legacy v1 API; Google Fonts uses CSS @font-face under the hood; Next.js (next/font/google) uses Google Fonts (v2 API) with self-hosting via build tools
Me: From https://www.w3schools.com/css/css_font_google.asp
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Sofia">
---snipped---
Later parts of the page talk of font effects like "fire" which are used with CSS classes like "font-effect-fire".
Fascinating! But how does it work? How does a font get loaded through a CSS stylesheet load (link element)? W3Schools does not get into those details. It stops at how to use them. Pl. respond to my questions above.
Gem: The <link> tag does not download the font file directly. Instead, it downloads a tiny, dynamically generated CSS stylesheet containing @font-face rules that tell the browser where to fetch the actual font file (usually a .woff2 binary) and what name to give it.
1. How the Font Gets Loaded (Two-Step Process)
When the browser parses <link rel="stylesheet" href="[https://fonts.googleapis.com/css?family=Sofia](https://fonts.googleapis.com/css?family=Sofia)">, four things happen in sequence:
- Browser requests the CSS: Your browser sends an HTTP GET request to Google's server, including its
User-Agentheader. - Google generates a tailored CSS file: Google's server inspects your
User-Agentto pick the most compact font format your browser supports (typicallywoff2for modern browsers) and sends back a small CSS file containing an@font-facedeclaration: (Inserted line break(s) below to prevent horizontal scroll issue.)
@font-face {
font-family: 'Sofia';
font-style: normal;
font-weight: 400;
src: url(https://fonts.gstatic.com/s/sofia/v14/8QIHdirahM3j_su5uI0.woff2)
format('woff2');
unicode-range: U+0000-00FF, U+0131, /* ... */;
}
- Browser registers the name, but waits: Seeing
@font-facedoes not immediately download the.woff2file. The browser simply registers"Sofia"in its internal font table. - Your CSS triggers the actual download: When the browser encounters
body { font-family: "Sofia", sans-serif; }and sees text on the page that needs to be rendered in"Sofia", it finally makes a second network request tofonts.gstatic.comto download that.woff2file and paints the text with it.
(If you paste [https://fonts.googleapis.com/css?family=Sofia](https://fonts.googleapis.com/css?family=Sofia) directly into your browser's address bar, you can read the exact @font-face CSS Google sends back.)
2. How font-effect-fire Works
There is no special font-file magic behind the "fire" effect—it is just plain CSS appended to that same dynamically generated stylesheet.
When you add &effect=fire to the URL ([https://fonts.googleapis.com/css?family=Sofia&effect=fire](https://fonts.googleapis.com/css?family=Sofia&effect=fire)), Google's server sees the effect query parameter and tacks a regular CSS class rule onto the bottom of the returned CSS file:
.font-effect-fire {
text-shadow: 0 -0.05em 0.2em #FFF,
0.01em -0.02em 0.15em #FE0,
0.01em -0.05em 0.15em #FC0,
0.02em -0.15em 0.2em #F90,
0.04em -0.20em 0.3em #F70,
0.05em -0.25em 0.4em #F70,
0.06em -0.2em 0.9em #F50,
0.1em -0.1em 1.0em #F40;
color: #ffe;
}
Adding class="font-effect-fire" to an HTML element simply applies that stacked text-shadow glow—it even works on any font, not just Google Fonts.
Quick Modern-Practice Note (W3Schools vs. Production Apps)
W3Schools is still showing Google Fonts' legacy v1 API (/css?family=Sofia), which is where &effect=fire lives. In modern JS apps, you will usually see two differences:
- Google Fonts v2 API (
/css2): Uses[https://fonts.googleapis.com/css2?family=Sofia&display=swap](https://fonts.googleapis.com/css2?family=Sofia&display=swap)(adding&display=swapso the browser shows the fallback font immediately instead of invisible text while the.woff2downloads). The oldeffect=presets are rarely used in production UIs. - Self-hosting via build tools: Modern frameworks like Next.js (
next/font/google) download the.woff2files at build time and serve them from your own domain with generated@font-facerules, eliminating the extra runtime round-trip to Google's servers.
Me: @font-face seems to be an advanced CSS rule. I am not sure if W3Schools even covers it. I don't recall seeing it in the web app codebases I read over past 2 to 3 years. ... I recall next/font/google in Next.js from previous project(s) I read/developed. As expected, Next.js brings in that useful performance optimization.
Gem: W3Schools actually does cover @font-face, though it tucks it away much later under its CSS Advanced → CSS Custom Fonts section rather than in the basic Fonts chapter.
The reason you rarely see raw @font-face declarations in modern web app codebases is that the ecosystem now treats it almost like "assembly language" for web fonts—it is still running under the hood everywhere, just generated automatically by higher-level tools:
- Framework loaders (
next/font/google,next/font/local): Next.js fetches the.woff2files at build time, bundles them with your static assets, and generates the@font-facerules behind the scenes. - npm font packages (
@fontsource/*): Common in Vite, React, and Astro projects—developers simply runimport '@fontsource/inter', and the package supplies the pre-written@font-faceCSS and local font files. - Google Fonts
<link>tags: Google's servers generate the@font-facerules dynamically on the fly. - System font stacks: Many lightweight apps and PWAs skip custom web fonts entirely (just like your Scratchpad
index.htmldoes with-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, ...).
next/font/google actually packs in two big optimizations beyond just eliminating the runtime round-trip to Google's servers: it keeps font requests strictly on your own domain (which avoids extra DNS/TLS handshakes and third-party privacy concerns), and it automatically calculates CSS fallback overrides (size-adjust, ascent-override) so the temporary system font matches the custom font's exact dimensions—preventing the page text from jumping around (Cumulative Layout Shift) when the web font finishes loading.
Today, you pretty much only write @font-face by hand if you are self-hosting a custom .woff2 file inside a plain Vanilla HTML/CSS project with no build step.
Me: Had a look at CSS Custom Fonts page of W3Schools. Interesting page! I don't want to get into details of it but good to know that even W3Schools has some coverage of it (in Advanced section).
I recall using/seeing import '@fontsource/inter' in some app codebases I read/wrote. Hmm. Interesting that they use @font-face CSS besides their local font files.
Good. I wanted only a top-level view of how @font-face works and I think I have got that. Thanks.
Gem: You're welcome! Having that top-level mental model—that Google Fonts, @fontsource/*, and next/font/google are all just different ways of delivering @font-face rules and .woff2 files—connects all the pieces cleanly without needing to memorize the low-level syntax. ...
'Classic Web Font Mode' Font Awesome icons use @font-face under the hood along with fa* classes; Modern React/Next.js/Tailwind apps have largely moved to inline SVG components for icons
Me: https://www.w3schools.com/css/tryit.asp?filename=trycss_icons_fa has this code:
<script src="https://kit.fontawesome.com/a076d05399.js" crossorigin="anonymous"></script>
...
<i class="fas fa-cloud"></i>
---snipped---
I have used font awesome icons in similar manner but without knowing how it works. (Later update: I am not sure if I used <i> way of using it.) Can you explain how above code works?
Gem: This code works by building directly on the @font-face mechanism we just covered—it treats every icon as a text character (glyph) inside a custom web font, rather than an image.
Step-by-Step: How the Classic Web Font Mode Works
- The
<script>tag loads the assets: Font Awesome "Kits" use a small JavaScript loader ([kit.fontawesome.com/...js](https://kit.fontawesome.com/...js)) instead of a static<link>tag. When the script runs, it injects Font Awesome's CSS stylesheet into your<head>. @font-faceregisters the icon font: Just like Google Fonts, that injected stylesheet contains@font-facerules pointing to.woff2font files—except instead of lettersA,B,C, those font files contain vector drawings of clouds, hearts, and cars mapped to special Unicode slots (the Private Use Area)..fasswitches to the icon font: The first class (fas= Font Awesome Solid) tells the browser to use that icon font and resets<i>'s default italics:
.fas {
font-family: "Font Awesome 6 Free";
font-weight: 900;
font-style: normal;
display: inline-block;
}
.fa-cloudinserts the character via CSS::before: Even though<i class="fas fa-cloud"></i>is completely empty in your HTML, the second class injects the specific Unicode character using a CSS pseudo-element:
.fa-cloud::before {
content: "\f0c2"; /* Unicode slot for the cloud glyph */
}
- Why
font-sizeandcolorwork: Because the browser literally renders that cloud as a single character of text, standard text properties likefont-size: 48pxandcolor: redresize and recolor it sharply at any scale.
The Other Mode: SVG + JS
Font Awesome Kits also have a toggleable SVG + JS mode. When a Kit is configured that way, the <script> scans the DOM after the page loads, finds every <i class="fas fa-cloud"></i>, and replaces it with an inline <svg> element. Font Awesome sets those SVGs to height: 1em and fill: currentColor, which is why style="font-size:48px; color:red;" still works identically even when no icon font is used.
Two Quick Notes for Your Refresher
- Why the
<i>tag? In HTML,<i>originally stood for italic (now idiomatic text), not icon. Font Awesome simply popularized repurposing<i>because it is short to type. Using<span class="fas fa-cloud"></span>works identically, and modern accessibility practice addsaria-hidden="true"to decorative icons so screen readers don't try to read them. - Modern JS app trend: Loading an entire icon font (or a Kit script) means downloading metadata for hundreds of icons even if you only use five. Modern React/Next.js/Tailwind apps largely moved to inline SVG components (like
lucide-react, Heroicons, or@fortawesome/react-fontawesome) so the bundler tree-shakes out unused icons and ships only the exact SVG paths you render—the same inline<svg>approach used in your Scratchpadindex.html.
Me: Very interesting that this code too uses the @font-face mechanism and ::before CSS pseudo-element. ... I recall using Heroicons and font awesome icons in React apps on lines you mentioned. Interesting that that uses inline SVG and avoids download of metadata for hundreds of icons. I don't recall using <i> tag then.
Gem: Right—in React, you never touch the <i> tag because libraries like Heroicons (@heroicons/react) and @fortawesome/react-fontawesome export each icon as a regular component (like <HeartIcon className="size-6"/> or <FontAwesomeIcon icon={faCloud} />) that renders directly to an inline <svg> in the DOM.
That gives you two clean wins over the classic W3Schools icon-font approach:
- Tree-shaking: Only the specific SVG path strings you import make it into your final JavaScript bundle—no external stylesheet, no
.woff2icon font download, and no unused icon metadata. - Cleaner HTML & styling: You get a real
<svg>element styled directly with Tailwind utilities (size-6 text-red-500) instead of hijacking an<i>tag with a::beforepseudo-element.
It is another classic case of W3Schools teaching the older, zero-build HTML/CSS pattern while modern JS frameworks have quietly moved to a much cleaner component-based architecture. ...
How to use Font Awesome icons as SVG in Vanilla JS apps
Me: In Vanilla Js if I want to use Font Awesome icons as SVG, how do I do it?
Gem: In Vanilla JS, there are three ways to use Font Awesome icons as SVGs, depending on how many icons you need and whether you want zero external dependencies:
| Approach | Best For | Pros / Cons |
|---|---|---|
1. Copy-paste inline <svg> |
Small apps / PWAs using ~5–20 icons | Zero dependencies, works offline, smallest payload. Slight HTML clutter if the same icon is repeated often. |
2. Inline SVG sprite (<symbol> + <use>) |
Small apps reusing the same icons in multiple places | Zero dependencies and keeps HTML clean by defining each <path> once. |
| 3. Font Awesome SVG + JS (Kit or CDN) | Larger sites using dozens of icons without a build step | Familiar <i class="fa-solid fa-cloud"></i> syntax; JS swaps it to <svg> at runtime. Heavy download unless you use a custom Kit. |
1. Copy-Paste Inline SVG (Best for Zero-Dependency Vanilla JS)
This is the exact pattern used for the inline <svg> icons in your Scratchpad index.html, and it works identically with Font Awesome:
- Search for a free icon on
fontawesome.comand click it. - Switch to the SVG tab and copy the
<svg>...</svg>snippet. - Paste it into your HTML, add a class, and set
fill: currentColorin CSS so it inherits text color automatically (Font Awesome's copied SVG omitsfillby default, which makes it render black).
<button class="icon-btn">
<svg class="fa-icon" aria-hidden="true" viewBox="0 0 640 512">
<path d="M0 336c0 79.5 64.5 144 144 144l368 0c70.7 0 128-57.3 128-128..."/>
</svg>
Sync
</button>
.fa-icon {
width: 1em; /* Scales automatically with button/text font-size */
height: 1em;
fill: currentColor; /* Inherits the parent's CSS color */
vertical-align: -0.125em;
}
2. SVG Sprite (<symbol> + <use>)
If you use the same icon in several places (for example, inside buttons and inside a Help modal), put the copied <path> data once inside a hidden <svg> block at the top of <body>, then reference it by ID:
<!-- Define once (hidden) -->
<svg style="display: none;">
<symbol id="icon-cloud" viewBox="0 0 640 512">
<path d="M0 336c0 79.5 64.5 144 144 144l368 0c70.7 0 128-57.3 128-128..."/>
</symbol>
</svg>
<!-- Reuse anywhere -->
<svg class="fa-icon" aria-hidden="true">
<use href="#icon-cloud"></use>
</svg>
3. Font Awesome SVG + JS via Kit or CDN
If you want the convenience of class names without manually copying SVG paths, load Font Awesome's JavaScript file instead of its CSS file (or set your Font Awesome Kit to SVG mode in your Font Awesome dashboard):
(Inserted line break(s) below to prevent horizontal scroll issue.)
<!-- Via a Font Awesome Kit (configured to SVG mode) -->
<script src="https://kit.fontawesome.com/YOUR_KIT_CODE.js" crossorigin="anonymous">
</script>
<!-- Or via CDN (loads the full solid icon set as JS) -->
<!-- <script defer
src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/js/solid.min.js">
</script> -->
<!-- <script defer
src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/js/fontawesome.min.js">
</script> -->
Then write standard icon tags in your HTML:
<i class="fa-solid fa-cloud" style="font-size: 2rem; color: steelblue;"></i>
When the page loads, Font Awesome's script finds every <i> tag and replaces it in the DOM with an inline <svg> (leaving the original <i> commented out). The catch with the CDN all.min.js / solid.min.js route is payload size—it downloads the SVG path data for every icon in that style, which is why Option 1 or Option 2 is usually the better fit for lightweight Vanilla JS apps.
Bootstrap and Google provide official SVG versions of their icons for Vanilla JS
Me: https://www.w3schools.com/css/css_icons_bootstrap.asp and https://www.w3schools.com/css/css_icons_google.asp show Bootstrap and Google icons used in similar way to Font Awesome page of W3Schools. Perhaps what you mentioned about above ways to use Font Awesome as SVG are available for Bootstrap and Google as well.
Gem: Yes—both Bootstrap and Google provide official SVG versions of their icons for Vanilla JS, and in fact both are even more SVG-friendly than the older icon-font setups shown on those two W3Schools pages.
Vanilla JS SVG Support Across the Three Libraries
| Library | Inline <svg> Copy-Paste |
SVG Sprite (<symbol> + <use>) |
JS Runtime Swapper (<i> → <svg>) |
|---|---|---|---|
Bootstrap Icons (icons.getbootstrap.com) |
Yes (primary method). Built SVG-first; every icon page has a one-click Copy HTML <svg> button (already includes fill="currentColor"). |
Yes (official). Ships a ready-made bootstrap-icons.svg sprite file out of the box. |
No. Doesn't need one since inline SVG and sprites are first-class. |
Google Material Symbols ([fonts.google.com/icons](https://fonts.google.com/icons)) |
Yes. Click any icon, customize weight/fill, and download the .svg file (or copy its markup) to paste inline. |
Yes (manual). Put the downloaded <path> elements into your own <symbol> block. |
No. Offers either direct SVG files or the Google Fonts icon stylesheet. |
Font Awesome (fontawesome.com) |
Yes. Copy from the icon's SVG tab (add fill: currentColor in CSS). |
Yes (manual). Same <symbol> + <use> approach. |
Yes. Font Awesome Kits / CDN JS can auto-replace <i> tags with <svg>. |
(Bonus for Vanilla JS: Bootstrap Icons is completely standalone—you don't need the Bootstrap CSS framework to copy-paste its SVGs, and unlike Font Awesome's raw SVGs, Bootstrap's snippets already come with width="16" height="16" fill="currentColor" ready to go.)
Two W3Schools-vs-Modern-Practice Notes
Both of those W3Schools pages are showing noticeably dated approaches:
- Bootstrap Icons page: W3Schools still teaches Bootstrap 3 Glyphicons (which required loading Bootstrap 3's entire stylesheet). Bootstrap dropped Glyphicons in Bootstrap 4 back in 2018 and replaced them with the separate, SVG-first Bootstrap Icons library.
- Google Icons page: W3Schools shows the legacy Material Icons web font. (One neat technical twist compared to Font Awesome: instead of
::beforepseudo-elements with Unicode codes, Google's icon font uses typographic ligatures—so typing the plain wordcloudinside<i class="material-icons">cloud</i>tells the font engine to swap the 5-letter word for the single cloud glyph.) Google's current replacement is Material Symbols ([fonts.google.com/icons](https://fonts.google.com/icons)), which adds variable font axes (weight, fill, grade) alongside direct SVG downloads.
For zero-dependency Vanilla JS apps, copying inline <svg> snippets directly from Bootstrap Icons, Material Symbols, Heroicons, or Lucide (lucide.dev) is the cleanest modern pattern—no external CDN requests, full offline PWA support, and zero unused icon bloat.
W3Schools pages on CSS Icons have learning and (legacy) code-reading value but for new production work, inline SVGs or framework SVG components are better
Me: So the W3Schools pages on Font Awesome, Bootstrap and Google can be noted as 'dated' with better SVG approaches available. However, the W3Schools page shows how it can be used with CSS and to that extent it may still have some learning-only (not to use in production) value. Am I on right track?
Gem: Yes, you are on the right track—with one small nuance separating what is strictly obsolete from what is simply legacy but still seen in the wild:
- Bootstrap Glyphicons (W3Schools' Bootstrap page): Strictly obsolete. Bootstrap dropped Glyphicons in v4 (2018) in favor of the standalone, SVG-first Bootstrap Icons library, so there is no reason to use Glyphicons in production.
- Font Awesome & Google Icon Fonts: Dated compared to inline SVGs and tree-shaken SVG components (Heroicons, Lucide,
@fortawesome/react-fontawesome) for modern JS apps and offline-first PWAs. That said, icon fonts aren't completely dead in production—you will still encounter them in legacy codebases, CMS themes, quick prototypes, and occasionally with Google's newer Material Symbols variable font (when a site wants to smoothly animate icon weight or fill with CSS).
So your takeaway is spot on: those W3Schools pages have real learning and code-reading value—they demonstrate how CSS treats icon glyphs like text (font-size, color, @font-face, ::before, and ligatures) and help you recognize <i class="fas ..."> when you run into older codebases—even though for new production work, inline SVGs or framework SVG components are the better default.
Split personality of em sizing unit: "Inherited font size" on font-size but "my own font size" everywhere else
Me: 30 Nov. ... https://www.w3schools.com/css/css_font_size.asp says, "The em unit is relative to the font size of the parent element. So, if the parent element has a font size of 16px, then 2.5em would result in 40px." ...
MDN https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/font-size#ems says:
...
In this case, the font size of <p> elements will be double the computed font-size inherited by <p> elements.
...
Me: Without getting too deep into the details of your response, the key confusion I had was ... font-size property associated with a <p> element, applies to <p>. Thus when we say font-size: 32px; that 32px directly applies to associated element without any inheritance/parent coming into the picture. But when we use em unit for font-size, then we get into computation involving inherited font-size. And as you pointed out, when we use em unit for other properties like padding, the computation involves the associated element's font-size property which may be different from its parent's font-size property. Am I on right track now?
Gem: Yes, you have it 100% right. That is the exact mental model.
Seen together on a single <p> element (assuming <body> is 16px):
p {
font-size: 2em; /* Multiplies inherited size (16px) → 32px */
padding: 1em; /* Multiplies <p>'s own computed font-size (32px) → 32px */
}
If you instead wrote font-size: 32px;, inheritance is bypassed completely for the text size, and padding: 1em; still reads <p>'s own 32px.
That split personality of em—meaning "inherited font size" on font-size, but "my own font size" everywhere else—is one more reason modern CSS favors rem, which always means the root <html> font size with zero exceptions.
Jargon clarity for style and color from HTML/CSS standards POV and JavaScript DOM POV
Me: Clarifying jargon stuff: From HTML/CSS standards point of view: style is an attribute of an HTML element and color is a property of the style (attribute).
In JS DOM, the style (HTML) attribute of an HTML element is accessible as style (JS) property of the (JS) HTMLElement object. Further, the color (CSS) property of (CSS) style is accessible as a color (JS) property of the style (JS) property (whose value is an object) of the (JS) HTMLElement object. Am I accurate here?
Gem: You are very accurate—you have the exact mental model of how HTML attributes, CSS properties, and JS DOM objects map to one another, with just one small wording refinement on the CSS side:
- HTML / CSS:
styleis an HTML attribute on the element. Strictly speaking,coloris a CSS property (not a "property of thestyleattribute"), and thestyleattribute's value is a string of CSS declarations (e.g.,style="color: red;") that sets those CSS properties inline. - JS DOM: Spot on. On the
HTMLElementobject,element.styleis a JS property whose value is aCSSStyleDeclarationobject reflecting the HTMLstyleattribute—andelement.style.coloris a JS property on that object mapping to the inline CSScolorproperty.
| Layer | style |
color |
Example |
|---|---|---|---|
| HTML | Global HTML attribute | Part of the attribute's string value | <p style="color: red;"> |
| CSS | Inline style declaration block | CSS property | color: red; |
| JS DOM | JS property on HTMLElement (returns a CSSStyleDeclaration object) |
JS property on that CSSStyleDeclaration object |
el.style.color = "red" |
Two quick practical details that pair well with this mental model:
- Hyphenated CSS properties become camelCase in JS: Because
-is a minus operator in JavaScript, CSSbackground-colormaps toel.style.backgroundColor(andfont-sizetoel.style.fontSize). el.styleonly sees inline styles: Readingel.style.coloronly returns what is set in the HTMLstyleattribute (or set earlier viael.style.color = ...), not styles coming from<style>blocks or external.cssfiles. To read the final active color regardless of where it came from, you usegetComputedStyle(el).color.
CSS pseudo-classes allow for selecting elements by interactive states (:hover); Pseudo-classes are not limited to interactive states; Element state is frequently styled without pseudo-classes
Me: (W3Schools) CSS Links seems to be the first page in its tutorial covering state. It jumps into the topic in the section "Styling Links Depending on State" without an intro of state in general.
MDN does better I think. In its CSS getting started: Styling things based on state section, it states, "The final type of styling we shall take a look at in this tutorial is the ability to style things based on their state. A straightforward example of this is when styling links."
Gem: MDN's framing builds a much stronger mental model. W3Schools treats state as a "links feature" first and waits until much later in the tutorial to introduce pseudo-classes as a general concept, which can make CSS feel like a pile of disconnected special cases.
(Later update suggested by Gem: In CSS, browser-tracked state is handled by pseudo-classes (single-colon selectors like :hover). Links just happen to be the classic introductory example because on the early web, <a> tags were practically the only interactive elements on a page.)
Two modern-practice details worth keeping in mind alongside that W3Schools Links page:
- Keyboard focus is missing from the classic 4 states: W3Schools focuses on
:link,:visited,:hover, and:active(often memorized as the LVHA order, since CSS cascade rules mean later declarations win when two states overlap—like hovering over a visited link). In modern web apps,:focus-visibleis just as important: it lets you style a clear focus outline for keyboard users tabbing through links and buttons without triggering a focus ring on ordinary mouse clicks. - The exact same mechanism drives all UI interactivity: Once you view state as a general CSS concept rather than a link-specific one, the rest of interactive styling clicks into place—buttons (
:hover,:active,:disabled), form inputs (:checked,:invalid,:focus), and even parent containers (:focus-within).
Tailwind CSS actually reflects MDN's mental model directly: prefixes like hover:underline, focus-visible:outline-2, and disabled:opacity-50 are just 1-to-1 wrappers around CSS pseudo-classes, applying the exact same state pattern uniformly across links, buttons, and form controls.
Me: Neither seems to introduce the pseudo-class term at the above stages. A later MDN Pseudo-classes and pseudo-elements: What is a pseudo-class? section introduces it, "A pseudo-class is a selector that selects 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."..."Pseudo-classes are keywords that start with a colon. For example, :hover is a pseudo-class."
A later W3Schools lesson CSS Pseudo-classes states, "A CSS pseudo-class is a keyword that can be added to a selector, to define a style for a special state of an element." ... "Pseudo-classes are always denoted by a single colon (:) followed by the pseudo-class name:"
I think it would have been nice if they had simply mentioned pseudo-class in the above initial lessons, and said details are covered later on. Ur view pl.
Gem: I agree with you—a single parenthetical signpost like "these colon-prefixed selectors are called pseudo-classes, which we'll cover in detail later" is almost always the better teaching choice.
Tutorial authors usually hold the term back out of progressive disclosure for complete beginners. In an introductory lesson, a newcomer is already juggling element, attribute, selector, property, and class. Dropping "pseudo-class" right away can sound needlessly academic and trigger a tangent before the learner has even styled their first hover state.
The downside—which you just ran into—is that for anyone who learns by building an accurate mental model, withholding the real name creates unnecessary friction. Giving the term early with a "details later" note costs a beginner almost nothing, while giving an analytical reader three immediate benefits:
- A search handle: You immediately know what to look up in MDN or ask about if you want to dig deeper.
- An intuitive mental hook: The name itself is actually helpful once you hear it—a "pseudo-class" behaves as if the browser temporarily slapped a hidden CSS class (like
.is-hoveredor.is-visited) onto the element whenever that state is active. - Pattern recognition: When you later hit
:first-child,:focus-visible, or:disabled, they immediately snap into the same mental drawer asa:hoverinstead of feeling like brand-new syntax.
Both MDN and W3Schools lean heavily toward smoothing the ramp for first-time learners, so they occasionally trade away that upfront structural clarity. In your own notes, tagging a:hover as a pseudo-class right from the Links section fixes that gap cleanly. ...
Me: Both use the term 'state' in their introductory lessons. I wonder whether that is a formal CSS term. If so, are all states pseudo-classes and vice-versa?
Gem: "State" is primarily a descriptive, conceptual term in CSS rather than a formal syntax category—and no, the relationship with pseudo-classes is not 1-to-1 in either direction.
1. Is "state" a formal CSS term?
In the W3C Selectors specification, "pseudo-class" is the formal term, defined broadly as a way to select elements based on "information that lies outside of the document tree or that cannot be expressed using the other simple selectors."
The spec uses the word "state" informally to describe some of those conditions (like whether a button is hovered or a checkbox is checked), rather than defining "state" as a standalone CSS construct. (The one modern exception is the newer :state() pseudo-class, which lets Web Components expose custom JS-managed states to CSS—e.g., my-toggle:state(checked).)
2. Are all pseudo-classes "states"? — No
Many pseudo-classes have nothing to do with an element's interactive or dynamic state:
- Tree-structural:
:first-child,:nth-child(2n),:empty,:root— match based on position in the HTML hierarchy. - Logical / matching:
:not(),:is(),:where(),:has()— combine or filter other selectors. - Linguistic:
:lang(en),:dir(rtl)— match based on language or text direction.
(Notice how that MDN beginner quote stretched the word "state" to include "being the first element of their type" just to give newcomers a single umbrella definition. Technically, :first-child is a structural position, not a state.)
3. Are all "states" pseudo-classes? — No
In real-world CSS and modern JS apps, element state is frequently styled without pseudo-classes:
- HTML / ARIA / Data attributes:
[aria-expanded="true"],[data-state="open"], or[open]on<details>/<dialog>— very common in modern React component libraries (like Radix UI / Headless UI). - JS-toggled CSS classes:
.is-open,.active,.loading— the classic Vanilla JS pattern. - Environment / user-preference states:
@media (prefers-color-scheme: dark)or@media (prefers-reduced-motion: reduce)— handled by media queries, not pseudo-classes.
| Question | Answer | Quick Example |
|---|---|---|
| Is "state" a formal CSS construct? | Mostly no (descriptive concept; :state() is a niche Web Components addition) |
— |
| Are all pseudo-classes states? | No | :nth-child(), :not(), :has() |
| Are all states pseudo-classes? | No | [aria-expanded="true"], [data-state="open"], .is-active |
So the clean mental model is: pseudo-classes are CSS's built-in mechanism for selecting elements by browser-tracked conditions—many of which happen to be interactive states (:hover, :focus-visible, :checked), while others are purely structural or logical.
In modern apps, CSS standalone class selectors (.a) are standard, while tag-qualified class selectors (ul.a) are generally avoided
Me: 1 Dec. ... https://www.w3schools.com/css/tryit.asp?filename=trycss_list-style-type_ex has:
ul.a {list-style-type: circle;}
When the class is used, the code is:
<ul class="a">
I typically have seen CSS code defining class separately like:
.a {...}
Ur views pl.
Gem: Your instinct matches modern CSS best practice: standalone class selectors (.a) are the standard in production codebases, while tag-qualified class selectors (ul.a) are generally avoided.
ul.a (with no space) is a compound selector meaning "any <ul> element that also has class="a"." It is completely valid CSS, and W3Schools likely used ul.a / ol.c in that demo just to make it visually obvious in the stylesheet which rules target unordered vs. ordered lists.
| Aspect | .a (Standalone Class) |
ul.a (Tag-Qualified Class) |
|---|---|---|
| Matches | Any element with class="a" |
Only <ul> elements with class="a" |
| Specificity | (0, 1, 0) |
(0, 1, 1) — slightly higher |
| Modern norm | Preferred default | Rarely used; mostly legacy or edge cases |
Why Modern CSS Prefers .a Over ul.a
- Decouples CSS from HTML tags: If you later change
<ul class="steps">to an<ol class="steps">,.stepskeeps working seamlessly, whereasul.stepssilently stops applying. - Keeps specificity flat: Because
ul.ahas specificity(0, 1, 1), a later single-class override like.no-bullets { list-style-type: none; }((0, 1, 0)) will lose toul.a, even if.no-bulletsappears lower in the stylesheet. Keeping selectors at single-class(0, 1, 0)prevents specificity wars. - One rare legitimate use case: Tag-qualifying is occasionally useful when the same class needs slightly different rules on two different HTML tags—for example,
a.btn { text-decoration: none; }alongsidebutton.btn { cursor: pointer; }—though even then, most modern codebases just put both properties in a single.btnrule.
(Quick syntax gotcha to keep in mind when reading code: ul.a with no space targets a <ul> with class a, whereas ul .a with a space is a descendant selector targeting any element with class a inside a <ul>.)
...
Me: I got the CSS syntax rule for this but my point is that it is not intuitive. But then lot of CSS syntax is not descriptive or intuitive.
Gem: That is a completely fair criticism—and a very common one among developers coming from traditional programming languages.
CSS was designed in the mid-1990s to be as terse as possible for hand-typing over slow connections, so it traded explicit, self-documenting syntax for cryptic punctuation. Making a single space the difference between ul.a (logical AND on the same element) and ul .a (a descendant somewhere inside ul) is a textbook example of syntax that prioritizes brevity over readability. Combinators like >, +, and ~, or the distinction between : and ::, have the exact same issue—nothing in the symbols themselves hints at what they do until you memorize them.
It is one of the quieter reasons modern workflows—whether standalone single-class CSS or Tailwind utilities—deliberately avoid complex selector gymnastics altogether. You still have to recognize the quirky syntax when reading tutorials or older stylesheets, even if you rarely choose to write it yourself.
Pseudo-class (e.g., :hover in a:hover) name indicates behavior as if browser dynamically added HTML class on the element behind the scenes
Me: https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/Pseudo-classes - "A CSS pseudo-class is a keyword added to a selector that lets you select elements based on information that lies outside of the document tree, such as a specific state of the selected element(s)."
I am curious about why this was named as pseudo-class. One would think it would have some relation to class but seems to be completely unrelated to it. Class name is user defined where pseudo-class name is a CSS defined keyword.
Gem: It is called a pseudo-class (literally "fake" or "virtual" class) because it behaves as if the browser dynamically added and removed a real HTML class on the element behind the scenes.
When you hover over a link, a:hover works conceptually as if the browser secretly modified your HTML to <a class="hover"> the moment your pointer entered, and stripped that class the moment your pointer left. Similarly, :first-child behaves as if the browser automatically tagged the first item in every list with class="first-child". You don't define those classes in your HTML—the browser supplies them virtually based on state or document structure.
The CSS specification didn't just borrow the word casually; it wired the exact same symmetry into CSS specificity and into its sibling term, pseudo-element:
| Concept | Real HTML Version | "Pseudo" (Browser-Simulated) Version | Specificity Weight |
|---|---|---|---|
| Class | .active (you put class="active" in HTML) |
:hover, :first-child (acts as if the browser added a class) |
(0, 1, 0) — identical |
| Element | <span> (you put <span> in HTML) |
::before, ::first-line (acts as if the browser wrapped/inserted a <span>) |
(0, 0, 1) — identical |
Once you see that 2×2 pairing—pseudo-class = phantom class, pseudo-element = phantom <tag>—the naming actually clicks together neatly. That said, your reaction is very common: without knowing that original 1996 W3C metaphor, the word "class" in "pseudo-class" looks completely disconnected from user-defined CSS classes.
Me: Interesting! I will need to ponder over it to grasp it properly but I think I am getting the drift for pseudo-class. The imagined pseudo-class addition to the element is done by the browser based on state/structure/... Developer only defines the CSS declaration block for the pseudo-class. Perhaps developer is not allowed (to) add :hover as a class to an element. Am I on right track here?
Gem: Yes, you are completely on the right track. That is the exact division of labor:
- The browser owns the matching: The browser continuously tracks the condition (mouse hovering, keyboard focus, first child in the DOM, etc.) and automatically turns the pseudo-class match on and off.
- You only write the CSS rule: As the developer, you write the selector and declaration block (
a:hover { color: red; }) to define what styles to apply whenever the browser says that condition is true. - You cannot manually add
:hoveras a class: Writing<a class=":hover">in HTML or callingel.classList.add(":hover")in JavaScript will not trigger the:hoverpseudo-class. HTML won't throw an error, becauseclassaccepts almost any string—it will simply treat":hover"as a literal, ordinary class name that has zero connection to the browser's:hoverstate.
The only place you can artificially force :hover on an element is inside browser DevTools (via the :hov toggle in the Styles pane) for debugging. In actual code, whenever you want to toggle a state yourself from JavaScript, you use a real class (like .is-open) or a data-* / ARIA attribute instead.
Me: Good. Taking it a little further, while I have never seen it being used in limited codebases I read, perhaps one could even use the universal selector for a pseudo-class - e.g *:hover {...}. Am I right?
Gem: Yes, you are right—*:hover is completely valid CSS. In fact, CSS lets you omit the * when it is combined with a pseudo-class, so *:hover and standalone :hover are functionally identical and have the exact same specificity of (0, 1, 0) (since * contributes zero specificity).
The reason you almost never see *:hover in real codebases comes down to how :hover behaves on nested elements: hovering over an element also hovers over every one of its ancestors. If you move your mouse over a <p> inside a <div> inside <body> inside <html>, all four elements match *:hover at the exact same time—which usually creates a chaotic cascade of highlights across the whole page.
Where the universal-selector + pseudo-class pattern does show up in real life:
- Global keyboard focus (
*:focus-visibleor:focus-visible): Very common in modern CSS resets to apply a consistent, accessible focus ring to any focusable element (links, buttons, inputs) across the entire site:
:focus-visible {
outline: 2px solid royalblue;
outline-offset: 2px;
}
- Quick layout debugging: Developers occasionally drop
*:hover { outline: 1px solid red; }into DevTools temporarily to visually inspect nested box boundaries as they sweep the mouse across a page.
Pseudo-element is like insertion of new element or rendering box; ::before adds content before element's content but within element; ::backdrop renders (box) outside element
Me: Now I am looking at pseudo-elements. You had said in an earlier response, "::before, ::first-line (acts as if the browser wrapped/inserted a <span>)" in the context of HTML <span> element.
In the case of ::before, it is like insertion of an element before selected element.
In the case of ::first-line, it is like part of selected element being wrapped in a new/inserted element.
Am I on right track here?
Gem: You are spot on with ::first-line, and very close on ::before—with one classic, important correction about where ::before gets inserted.
::before(the key correction): It does not insert a virtual element outside before the selected element (as a sibling). It inserts it inside the selected element as its first child—right before the element's content. (Similarly,::afterinserts a virtual last child inside the element, right after its content.)
<!-- What p::before conceptually creates (INSIDE <p>) -->
<p>
<span class="virtual-before"></span>
Actual paragraph text...
</p>
<!-- NOT outside as a sibling:
<span class="virtual-before"></span><p>Actual paragraph text...</p> -->
::first-line: Completely accurate. It behaves as if the browser dynamically wrapped whichever words currently land on the first rendered line inside a virtual<span>—and automatically re-wraps them if the viewport width or font size changes.
<!-- What p::first-line conceptually creates -->
<p>
<span class="virtual-first-line">Words on the first line</span>
rest of the paragraph text...
</p>
That "first child inside" detail for ::before (and ::after) explains two real-world CSS behaviors that otherwise look mysterious:
- It sits inside the element's box: A
::beforepseudo-element is drawn inside the element's border and padding, and it automatically inherits the element'scolorandfont-size(which is why Font Awesome's.fa-cloud::beforeworked inside<i class="fas fa-cloud"></i>). - It doesn't work on void elements: Because elements like
<img>,<input>, and<br>cannot contain children in HTML, they generally cannot render::beforeor::afterpseudo-elements.
Me: Oh! So the 'before' is before selected element's content rather than before selected element. Did I word that correctly?
Gem: Yes, you worded that accurately—::before means before the selected element's content (as its virtual first child), not before the element itself.
And ::after follows the exact same rule: after the selected element's content (as its virtual last child), still inside the element's box. That phrasing is a great mental anchor because the short names ::before and ::after are one of the most common sources of confusion in CSS.
Me: https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/Pseudo-elements says, "Note, browsers support single colon syntax for the original four pseudo-elements: ::before, ::after, ::first-line, and ::first-letter." Perhaps that would be used only in legacy code. Modern app code would use double-colon even for these 4 pseudo-elements. Am I right?
Gem: Yes, you are completely right—modern codebases, CSS linters (like Stylelint), and build tools consistently use the double-colon (::) syntax for all pseudo-elements, including those original four.
The single-colon exception only exists for historical backwards compatibility:
- CSS1/CSS2 origins: Early CSS used a single colon for both pseudo-classes (
:hover) and pseudo-elements (:before). CSS3 introduced::specifically to make the two visually distinct, and browsers retained single-colon support for those four so old websites wouldn't break. - Why you still see it in legacy code: For years, developers intentionally wrote
:beforeand:afterto support Internet Explorer 8 (which didn't recognize::). Once IE8 disappeared, that technical reason vanished—today, single colons on those four usually just signal older codebases or old muscle memory. - Newer pseudo-elements require
::: Anything introduced since CSS3—such as::placeholder,::marker,::selection, or::backdrop—only works with a double colon; browsers ignore single-colon versions of them.
Sticking strictly to : for pseudo-classes and :: for pseudo-elements is the clean modern standard.
...
(During headings review, Gemini mentioned edge cases like ::backdrop, which sits outside the element ...)
Me: ... Hmm. Some pseudo-elements add an element outside selected element! But then it must be immediately before or after selected element. Or is that also not the rule?
Gem: No—there is no rule that an outside pseudo-element must sit immediately before or after the selected element. Pseudo-elements don't exist in the HTML DOM at all; they exist in the browser's rendering/box tree, which gives CSS freedom to place them wherever a feature requires.
The clearest example is ::backdrop, used with native <dialog> modals, popovers, and fullscreen elements. When you open a <dialog> as a modal, dialog::backdrop creates a full-screen overlay (usually a semi-transparent dark scrim) in the browser's top layer—a special viewport-level rendering layer above the rest of the page. It is not inserted inside <dialog>, nor is it placed immediately before or after <dialog> in document flow; it sits behind <dialog> in stacking order (along the z-axis), covering the entire viewport.
| Placement | Examples | How the Browser Renders It |
|---|---|---|
| Inside the element (vast majority) | ::before, ::after, ::first-line, ::first-letter, ::placeholder |
Generated as a virtual child or wrapper inside the selected element's box. |
| Structurally inside, visually outside | ::marker (the bullet/number on <li>) |
Logically belongs inside <li> in the box tree, though by default (list-style-position: outside) it paints just outside the left edge of the box. |
| Outside in a separate layer | ::backdrop |
Rendered in the viewport's top layer directly behind the modal or fullscreen element, detached from normal document flow. |
...
Me: Just looked up ::backdrop in MDN. Hmm. it seems to be purely style. pseudo-element may not be appropriate name for it.
Gem: Your instinct makes sense—::backdrop carries no text or semantic content and exists purely for visual styling. The reason CSS models it as a pseudo-element rather than a style property on <dialog> comes down to boxes, not content.
Two practical design reasons drove that choice:
- It needs a second, independent CSS box: A
<dialog>already usesbackground,opacity,filter,transition, andanimationfor the modal box itself. The dimmed overlay behind it is a separate, viewport-sized box that needs its ownbackground,backdrop-filter: blur(4px),opacity, and fade-inanimation. Making::backdropa pseudo-element lets you apply the entire existing CSS property set to that second box, rather than CSS having to invent dozens of duplicate properties likebackdrop-background,backdrop-opacity, andbackdrop-animation. - It replaces a real, empty
<div>: Before native<dialog>and::backdrop, developers literally had to put an empty<div class="modal-backdrop"></div>in their HTML just to paint that full-screen scrim.::backdropis the browser generating that empty presentational<div>virtually so your HTML stays clean.
In CSS's mental model, the "element" in pseudo-element really means "a browser-generated box you can style," whether or not it contains text. You see the exact same pattern with ::before and ::after—in modern CSS, they are used with content: "" (empty content) all the time purely to draw decorative shapes, custom underlines, or hover overlays.
Me: (So) the element word meaning in pseudo-element seems to be stretched quite a bit beyond a normal element, for cases like ::backdrop. Do u agree with me?
Gem: Yes, I agree—if you measure it against what an HTML element actually is in the DOM, ::backdrop stretches the word "element" almost to its breaking point.
A real HTML element is a node in the document tree with tags, attributes, and a defined place in the parent-child hierarchy. ::backdrop has none of those: it has no tag, cannot hold text or child nodes, does not exist in the DOM, and does not even sit inside or adjacent to <dialog> in normal document flow.
The stretch comes down to historical naming lock-in. When the W3C coined the term pseudo-element in 1996 for ::first-line and ::first-letter, the metaphor of a "virtual <span>" fit reasonably well. Years later, as CSS needed selector hooks for purely visual, browser-generated boxes—like ::backdrop or ::placeholder—the CSS Working Group chose to reuse the existing :: syntax rather than invent a third category like "pseudo-box." So in modern CSS, "pseudo-element" has effectively become a catch-all label for any browser-generated rendering box you can style, even when the original "element" metaphor barely fits anymore.
Content generated via ::before or ::after is added to render tree (and accessibility tree), not to DOM tree; Use them strictly for decorative icons, symbols, or visual counters, and keep application data inside real DOM elements
Me: ::before used to add content will add content only to render tree and not DOM tree. Did I get that right? If so, how does JS code get to know what exactly is being shown to user?
Gem: Yes, you got that completely right. Content generated via ::before or ::after is added only to the browser's render tree (and the accessibility tree), never to the DOM tree.
Because the DOM is untouched, standard DOM inspection methods completely miss it:
el.textContent,el.innerText, andel.innerHTMLreturn only the actual DOM content.el.childrenandel.childNodesdo not include the pseudo-element.- JavaScript cannot get a node reference to
::beforeor attach event listeners directly to it.
How JavaScript Inspects ::before Content
While JavaScript cannot access ::before as a DOM node, it can query the browser's CSS styling engine for the pseudo-element's resolved styles—including its content value—by passing '::before' as the second argument to window.getComputedStyle(): (Inserted line break(s) below to prevent horizontal scroll issue.)
const el = document.querySelector('.alert');
const beforeStyles = window.getComputedStyle(el, '::before');
console.log(beforeStyles.content); // e.g., '"Warning: "'
// (includes literal quotes)
console.log(beforeStyles.color); // e.g., "rgb(220, 38, 38)"
A few details worth noting about how getComputedStyle(el, '::before').content behaves:
- Literal quotes: If
contentis a string, JavaScript receives it wrapped in quotes (e.g.,'"Warning: "'), whereas if no::beforeexists on the element, it returns'none'. - Evaluated values: If the CSS uses
content: attr(data-prefix)orcontent: counter(step),getComputedStyle()returns the final evaluated string shown to the user rather than the raw CSS expression.
Architectural Takeaway
Because ::before content bypasses the DOM—and therefore won't be picked up by normal DOM reads, innerText extraction, or standard search/scraping logic—web engineering best practice is to use ::before strictly for decorative icons, symbols, or visual counters, and keep any meaningful text or application data inside real DOM elements.
Me: Hmm. The takeaway is very important. In my quick browse-reading of W3Schools and MDN on pseudo-elements, I did not spot such vital information. Maybe it is there but I missed it.
Gem: You didn't miss much on a quick browse—W3Schools skips those architectural implications altogether, and MDN splits them across separate reference pages rather than putting the practical takeaway front and center.
Here is how those two references actually treat the topic:
- W3Schools: Sticks strictly to syntax and visual demos (like inserting an image or symbol before a heading). It doesn't go into DOM vs. render tree mechanics,
getComputedStyle(), or when not to use::before. - MDN's Pseudo-elements overview page: Notes in a single sentence that pseudo-elements aren't part of the DOM tree, without spelling out what that means for JavaScript scraping, DOM APIs, or application architecture.
- MDN's
::before,::after, andcontentpages: Tuck the practical guidance down in an Accessibility concerns section. There, MDN warns against putting meaningful content in CSS (recommending real HTML elements instead) and notes that screen readers do read::before/::aftertext unless you explicitly silence decorative symbols using the modern alt-text syntax (content: "★" / ""). - MDN's
window.getComputedStyle()page: Documents the optional secondpseudoEltparameter (getComputedStyle(el, '::before')), which is easy to overlook if you are only reading the CSS selector docs.
One more practical side effect that reinforces the same rule: browser Ctrl+F (Find in Page) also ignores text injected via ::before and ::after in most browsers. Between invisible DOM text, skipped page search, and screen-reader quirks, keeping real words in HTML and limiting ::before/::after to visual decoration saves a lot of subtle headaches.
Browser Ctrl+F (Find in Page) also ignores text injected via ::before and ::after in most browsers including Chrome
Me: OMG! Browser Ctrl+F ignores ::before / ::after injected text. I presume that's the case with Chrome. That's stunning! Give me test HTML page to test it now with Chrome.
(An iteration to improve the page(s)....) Me: It is as you said with one minor issue. As the test instructions are also on the page, some matches are found in the test instructions. So either modify the test instructions to reflect that OR can the test instructions be put in an accompanying page with a link to that page in the main page.
Gem: Putting the instructions in a separate file solves that cleanly—and also avoids a second subtle trap in the earlier page, where the <script> wrote getComputedStyle(p1, "::before").content into <pre id="output">, which itself injected "ALPHA_BEFORE: " into the DOM.
Save both files below in the same folder and open test.html in Chrome. The instructions link opens in a second tab so you can read the tokens there while running Ctrl+F on the clean test.html tab.
(In private repo, css\202612-quick-refresh-study\pseudo-elements folder has test.html and instructions.html)
1. test.html (Clean Test Page)
---snipped---
2. instructions.html (Accompanying Instructions)
---snipped---
On test.html, Chrome's Ctrl+F ignores both the CSS inside <style> and the data-tag="DELTA_ATTR" attribute, and deferring the <pre> output behind a button ensures the page starts with zero DOM occurrences of the pseudo-element tokens.
Me: I focused on before and after. These pages work as expected. Hmm. I had simply not known about this weird possibility in Chrome. Hmm. Quite a stunner! User will think Chrome has a big bug!
Gem: From an end user's perspective, it genuinely does look like a glaring browser bug—the words are sitting right there in bold red and blue on the screen, yet Ctrl+F insists they don't exist and the mouse refuses to highlight them.
Chromium actually has a famous bug report on this that has been debated for well over a decade. Browser engineers have largely held off on changing it because Chrome's Find-in-Page engine intentionally scans DOM text nodes, treating CSS-generated content as purely decorative—things like list markers, decorative quotation marks, or ornamental dividers that shouldn't clutter search results or copied text.
The catch is that the browser has no way to tell whether a developer used ::before for a decorative symbol or for real words like "Warning: " or "Sold Out". The moment a developer puts meaningful text into CSS content, they create an invisible UX trap where users cannot search or copy what is right in front of them—which is why keeping real words in HTML is such a firm rule in production web apps.
Comments
Post a Comment