Questions 161–180 of 193 · 0 of 20 on this page marked learned
161.html-css-0161Easyfresher
Which global attributes can go on any element, and which ones do you use most?
Global attributes such as id, class, lang, dir, title, hidden, inert, tabindex, contenteditable, translate and data-* work on any element. Use tabindex 0 or -1 only, prefer native controls, and do not put important information in title.
Full answer
Global attributes work on every HTML element. Knowing them avoids needless scripts and wrong markup.
id gives a unique name for links, labels, scripts and ARIA references. class gives a group name for styles. style sets inline styles and is best kept for dynamic values.
lang and dir set the language and text direction.
title gives advisory text, often shown as a tooltip. It is poor for important information, because keyboard and touch users usually cannot see it.
hidden hides an element, and inert makes an element and its children not interactive and hidden from assistive technology.
tabindex controls keyboard focus: 0 puts a non-interactive element in the natural order, and -1 makes it focusable by script only. Positive values change the order and should be avoided.
contenteditable, spellcheck and autocapitalize affect editing. draggable marks an element as draggable.
translate="no" tells translation tools not to translate the text. It suits brand names and code.
data-* stores custom data, and aria-* and role add accessibility information.
accesskey assigns a shortcut, but it clashes with browser and screen reader shortcuts, so it is rarely a good idea.
autofocus focuses an element on load, which can be disorienting, so use it carefully.
popover and slot serve newer features.
Many properties of the same name exist in JavaScript, such as el.hidden, el.tabIndex, el.translate and el.draggable.
The brand name is marked so that translation tools leave it alone. The div can be dragged and can receive focus from a script, but not from the Tab key. The inert button cannot be focused or clicked.
Prefer a real button or link to adding tabindex to a div.
Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
id, class and style identify and style an element.
lang and dir set language and direction; translate="no" protects brand names.
hidden and inert remove an element from view and interaction.
tabindex 0 and -1 are the safe values.
data-* stores custom data.
Common mistakes
Using title for information that users need.
Using positive tabindex values.
Adding tabindex to a div instead of using a button.
Follow-ups
What does tabindex="-1" do?
Why is accesskey rarely used?
Tips
Group the attributes: identity, language, visibility and focus, editing, custom data.
Give translate="no" as an example that people forget.
162.html-css-0162Easyfresher
What is structured data in HTML, and how do JSON-LD and microdata differ?
Structured data describes page content with the schema.org vocabulary. JSON-LD keeps it in a separate script element of type application/ld+json, and microdata marks the visible HTML with itemscope, itemtype and itemprop. Mark up only visible content, and use valid JSON.
Full answer
Structured data describes the meaning of page content in a form that programs can read. Search engines and other tools use it, for example to show a course with a rating, an event with a date, or a product with a price. The shared vocabulary is called schema.org.
There are two common formats.
JSON-LD is a script element with type="application/ld+json" that holds a JSON object. It is separate from the visible markup, so it is easy to write, generate and change. The keys @context and @type name the vocabulary and the kind of thing. The browser does not run it, because the type is not a script type. Most search engine guides prefer this format.
Microdata puts the data into the visible markup with attributes: itemscope starts a thing, itemtype names its type, and itemprop marks each property. The values come from the text of the elements, or from attributes such as content and href. It stays in step with the visible text, but it is mixed into the HTML and harder to maintain.
Rules that matter in both:
Mark up only what is visible on the page. Data that users cannot see can lead to penalties from search engines.
Valid JSON is needed: no comments and no trailing commas. A syntax error means the data is ignored.
Structured data does not guarantee a special search result. It makes the page eligible.
Check pages with the validators that search engines provide.
A script can read the JSON-LD with JSON.parse and gets an object whose type is Course. The microdata version gives the same name through the itemprop elements. The JSON-LD block is not drawn on the page.
Keep the structured data in step with the text that users see.
html
<script type="application/ld+json" id="ld">
{
"@context": "https://schema.org",
"@type": "Course",
"name": "HTML and CSS basics",
"description": "Start with tags and styles.",
"provider": { "@type": "Organization", "name": "Schoolabe" }
}
</script>
<div itemscope itemtype="https://schema.org/Course" id="md">
<h2 itemprop="name">HTML and CSS basics</h2>
<p itemprop="description">Start with tags and styles.</p>
</div>
Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
Structured data uses the schema.org vocabulary.
JSON-LD is a script block with JSON.
Microdata uses itemscope, itemtype and itemprop.
Mark up only visible content.
Invalid JSON means the data is ignored.
Common mistakes
Marking up content that is not visible on the page.
Writing invalid JSON in a JSON-LD block, such as a trailing comma.
Expecting structured data to force a rich result.
Follow-ups
Why does the browser not run a JSON-LD script?
What is schema.org?
Tips
Describe both formats briefly and say which one you prefer and why.
Mention the rule: mark up only visible content.
163.html-css-0163Mediummid
Which link rel values do you use in the head and on anchors, and what does each one do?
In the head, rel values include stylesheet, icon, manifest, canonical, alternate with hreflang, and the performance hints. On anchors, noopener and noreferrer protect the opener, and nofollow, ugc and sponsored tell search engines how to treat the link.
Full answer
The rel attribute names the relationship between the current page and the linked resource. It works on link elements in the head and on a and form elements.
Values on link in the head:
stylesheet loads CSS. icon gives the small image for the tab. manifest points to the web app manifest.
canonical names the preferred address when the same content has several. Search engines use it as a strong hint.
alternate points to another version. With hreflang it lists translations: <link rel="alternate" hreflang="hi" href="...">. With type it can point to a feed.
preload, prefetch, preconnect and dns-prefetch are performance hints.
prev and next mark pages of a series, but major search engines no longer use them. Keep normal links in the page.
Values on anchors, in a space-separated list:
noopener stops the new page from reaching window.opener. Current browsers apply it to target="_blank" by default, but writing it is still common.
noreferrer hides the referring address, and it also implies noopener.
nofollow asks search engines not to count the link. ugc marks links in user content and sponsored marks paid links. They can be combined.
external, author, license, help and me describe the target, and me is used for identity links.
A rel value the browser does not know is ignored. relList.supports("preload") tells whether a value is supported for that element.
The canonical link gives the one preferred address. The alternate link names the Hindi version. The anchor carries four values, and its relList shows them as a list.
Use only values that you mean, since wrong values can send the wrong signal to search engines.
Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
canonical names the preferred URL.
alternate with hreflang lists translations.
icon and manifest describe the site to the browser.
noopener and noreferrer protect the opener.
nofollow, ugc and sponsored describe link trust.
Common mistakes
Putting nofollow on all outgoing links without a reason.
Forgetting that the canonical link must be an absolute, correct address.
Using rel="prev" and rel="next" and expecting search engines to need them.
Follow-ups
What is the difference between nofollow, ugc and sponsored?
How can you test whether a rel value is supported?
Tips
Split the answer into head values and anchor values.
Name canonical, alternate with hreflang, noopener and nofollow.
164.html-css-0164Hardsenior
Why is HTML for email written differently from web pages, and what are the main rules?
Email is displayed by many clients with limited and different HTML and CSS support, so it uses nested layout tables, inline styles, no scripts, a width of about 600 pixels, images with alt text and fallbacks, and testing in real clients.
Full answer
A web page runs in a browser that you can test. An email is shown by many different mail programs, web mail sites and phone apps. Each one cleans, rewrites or limits the HTML in its own way, and some use old rendering engines with weak CSS support. The safe way to write email is to use the simplest markup that works everywhere.
Common rules:
No JavaScript. Mail programs remove scripts and most active content. Forms, video and many other features are not reliable either.
Layout with tables. Nested table elements with role="presentation" are still the most dependable layout method, because Flexbox and Grid have poor or unknown support in many clients. Use width, cellpadding, cellspacing and align attributes together with CSS.
Inline styles. Many clients remove or ignore style blocks in the head, and some remove media queries. A build tool usually inlines the CSS into style attributes. Keep a style block only for progressive extras such as responsive rules.
Fixed, narrow width. About 600 pixels is the usual maximum width, with max-width: 100% for small screens. Hybrid and fluid patterns add some flexibility.
Images need alt text, explicit width and height, and display: block. Many clients block images by default, so the email must still make sense without them. Do not put important text only in images.
Safe fonts with fallbacks, because web fonts are often not loaded. Use absolute https links, and a plain text version for clients that need it.
Dark mode can change colours in unexpected ways. Test with transparent images and avoid pure text-in-image designs.
Testing matters more than for the web. Check the email in real clients or with a testing service, because behaviour differs and changes over time. The claims here are general. Check the current support for each client that matters to you.
The inner table is 600 pixels wide and centred. All styles are inline, so a client that removes the head styles still shows the same look. The button is a link styled with padding, which works more widely than a form button.
This sample was checked in one browser only. It does not prove how any mail client will draw it.
Mail clients were not available, so the snippet was only run in Chrome. Support for CSS differs a lot between mail clients, so test in the clients your readers use. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
Mail clients rewrite and limit HTML and CSS.
Use nested tables with role="presentation" for layout.
Inline the CSS; head styles may be removed.
No JavaScript; images may be blocked, so add alt text.
Test in real clients.
Common mistakes
Relying on a style block in the head and on Flexbox or Grid.
Putting key information only in images.
Testing in one browser and assuming all mail clients will match.
Follow-ups
Why use role="presentation" on a layout table?
How would you test an email before sending?
Tips
Open with the reason: many different clients with limited and changing support.
List the main rules: tables, inline CSS, no scripts, fixed width, image alt and fallbacks.
165.html-css-0165Mediummid
How do you adjust fonts, quotes and line breaks for different languages on one site?
Set lang on the page and on foreign phrases, then use :lang() to choose font stacks, line height, quotes and line-breaking rules per language. Avoid letter-spacing on joined scripts, avoid fixed widths for labels, and test with real text.
Full answer
A site in several languages needs more than translated text. Each script has its own needs, and CSS can follow the lang attribute to adapt.
Select by language with :lang(). It matches the lang of the element or of its nearest ancestor that has one, so a set lang on the html element and on foreign phrases is the base of everything.
Useful adjustments:
Font stacks per language. A font made for Latin letters often has no glyphs for Hindi, Arabic or Chinese, and the browser then picks a fallback that may look out of place. Set a suitable stack: :lang(hi) { font-family: "Noto Sans Devanagari", sans-serif; }. Subset fonts so users download only what they need.
Line height. Scripts with tall marks, such as Devanagari or Thai, and dense scripts, such as Chinese and Japanese, often need a larger line-height than Latin text, around 1.6 to 1.8.
Quotation marks. The quotes property sets the marks used by q and by blockquote::before. German uses „ and “, French uses « and », English uses “ and ”. Without a rule, browsers pick marks for the language of the element.
Line breaking. Chinese and Japanese can break between most characters. word-break: keep-all keeps Korean words together. overflow-wrap: anywhere handles long strings in any language.
Letter spacing. Do not add letter-spacing to scripts that join letters, such as Arabic, because it breaks the joining.
Text size and direction. Use logical properties and the dir attribute for right-to-left languages, and expect that text length changes by language, so avoid fixed widths for labels.
Test with real text from each language, not with a placeholder.
The Hindi paragraph gets a taller line height. The German quote is drawn with the marks „ and “, and the French one with « and ». Each rule applies only where the language matches.
Check that the font actually has glyphs for the script, or the page will fall back to a different look.
Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
:lang() follows the lang attribute.
Different scripts need different font stacks and line heights.
quotes sets the quotation marks per language.
word-break: keep-all and overflow-wrap handle line breaks.
Do not add letter-spacing to Arabic.
Common mistakes
Leaving lang off, so no language rules can apply.
Using one Latin-only font stack for all languages.
Adding letter-spacing to Arabic text, which breaks the joined letters.
Follow-ups
What does the quotes property control?
Why is letter-spacing a problem for Arabic?
Tips
Say that :lang() depends on the lang attribute, so set it correctly first.
Give examples for font stacks, line height and quotes.
166.html-css-0166Mediummid
How do you animate an element open from height 0 to its natural height when height: auto cannot be animated?
height: auto cannot be interpolated. A grid with grid-template-rows going from 0fr to 1fr animates to the content height with no script, if the child has overflow: hidden and min-height: 0. Newer CSS can animate to auto directly, but check support and hide closed content from the keyboard.
Full answer
A transition needs two numbers to move between. height: 0 is a number, but height: auto is not, so transition: height jumps at the end and does not animate. This is a common need for accordions and expanding panels.
Options:
Animate max-height to a large value such as 500px. It works, but the speed is wrong when the content is shorter than the guess, and the panel can be cut when the content is taller. It is a rough fix.
Measure with JavaScript. Read scrollHeight and animate the height to that number, then set auto at the end. It is exact, but needs script and care when content changes size.
Animate a grid row. A grid container with grid-template-rows: 0fr becomes 1fr when open. The track size fr is a number, so it interpolates, and the track ends up as tall as the content. The child needs overflow: hidden and min-height: 0, so it can shrink to zero. This needs no script apart from toggling a class.
Newer CSS can animate to auto directly with interpolate-size: allow-keywords or with calc-size(). Check the support table before relying on it, and keep option 3 as the fallback.
Also remember accessibility: a closed panel should be hidden from the keyboard and from screen readers, for example with visibility: hidden after the transition, inert, or the hidden attribute, so its links are not focusable when it is closed. Respect reduced motion by shortening or removing the transition.
Closed, the panel has zero height. After the click, it grows over 0.3 seconds to the exact height of the three lines, with no number written in the CSS.
Add inert or visibility: hidden to the closed content when it holds links or buttons.
Checked in Chrome 156 only, by clicking and reading the height of the inner box after the change. The animation was not watched by eye. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
Auto is not a number, so it cannot be transitioned.
max-height is a rough workaround.
grid-template-rows 0fr to 1fr animates to the content height.
The child needs overflow: hidden and min-height: 0.
Hide closed content from keyboard and screen readers.
Common mistakes
Using max-height with a guessed value and getting wrong timing or cut content.
Forgetting min-height: 0 and overflow: hidden on the grid child.
Leaving links in a closed panel focusable.
Follow-ups
Why does the child need min-height: 0?
How would you hide the closed content from keyboard users?
Tips
Explain why auto cannot be animated, then list the options in order of quality.
Describe the 0fr to 1fr trick and its two required properties.
167.html-css-0167Hardsenior
What is the FLIP technique, and how does it animate a layout change cheaply?
FLIP measures the first position, makes the change, measures the last position, inverts with a transform so nothing seems to move, and plays the transform back to none. Layout runs once, and the animation changes only transform.
Full answer
Some changes cannot be animated with CSS because they are layout changes: reordering a list, moving an item to another container, or changing a grid. If you animate top, left or width, the browser must redo layout on every frame, which is slow. FLIP lets you animate such changes with transform, which is cheap.
FLIP stands for First, Last, Invert and Play.
First: measure the element's starting box with getBoundingClientRect().
Last: make the change in the DOM or in the classes, so the element is in its final place. Measure it again.
Invert: compute the difference between the two boxes, and apply a transform that moves the element back to where it was. At this point it looks as if nothing has moved.
Play: animate the transform to none. The element appears to travel from the old place to the new one.
The real layout has already changed at the start, so the work for layout is done once. The animation only changes transform, which the browser can draw on the compositor, often without redoing layout or paint on each frame.
Tips:
Use the Web Animations API (el.animate()), which gives a promise when the animation finishes, and avoids a forced style flush.
Read all positions first and write after, to avoid layout thrashing.
Scale changes can distort content, so animate size with care or use a separate approach.
Keep the time short and respect prefers-reduced-motion.
The View Transitions API does something similar for the browser, with less code, but it is newer, so check the support table.
After the call, the DOM order is B, C, A at once. Item A starts at the top and moves to the bottom, and B and C move up, all by transform. Each moving item has one running animation, and when it ends, nothing is left in the style.
Measure in the performance panel to see that layout runs once, and not once per frame.
Checked in Chrome 156 only. The check counted the running animations and the final order, not how smooth the motion looks. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
First, Last, Invert, Play.
Layout changes once; the animation uses transform.
Web Animations API gives control and a finished promise.
Read all positions before writing.
View Transitions can do similar work with less code.
Common mistakes
Animating top, left or width for a reorder and causing layout on every frame.
Reading and writing positions in turns, which forces layout many times.
Skipping a reduced motion rule.
Follow-ups
Why use getBoundingClientRect before and after the change?
How does the View Transitions API relate to FLIP?
Tips
Spell out First, Last, Invert, Play in one sentence each.
Say why transform is cheaper and that layout is done once.
168.html-css-0168Mediummid
How does element.animate() work, and when do you prefer it to CSS animations?
element.animate(keyframes, options) runs an animation and returns an Animation object with a finished promise, playback controls, currentTime and commitStyles(). Use it when values or timing come from script, and use CSS for simple state changes. Respect reduced motion.
Full answer
element.animate(keyframes, options) is a JavaScript method that runs an animation with the same engine as CSS animations and transitions. It returns an Animation object.
Keyframes are an array of objects, or an object of arrays: [{ opacity: 0 }, { opacity: 1 }]. Options are the usual timing values: duration in milliseconds, easing, delay, iterations, direction and fill.
The Animation object gives control that CSS does not:
finished is a promise that resolves when the animation ends, so you can chain steps with await.
play(), pause(), reverse(), cancel() and finish() control playback, and playbackRate changes the speed.
currentTime reads or sets the position, which allows scrubbing.
commitStyles() writes the final values into the element's style, so the result stays after the animation is removed. By default, an animation without fill: "forwards" removes its effect at the end.
element.getAnimations() lists the running animations, including CSS ones.
Prefer it when:
The values are known only in script, such as a measured distance (as in FLIP).
You need to wait for the end, to remove an element or start the next step.
You need to pause, reverse or scrub.
Prefer CSS when the animation is a simple state change, because CSS is easier to read and to override with media queries. Both can run off the main thread when only transform and opacity change.
Respect the user's reduced motion setting: check matchMedia("(prefers-reduced-motion: reduce)").matches and skip or shorten the animation.
The animation fades the box from full opacity to 0.2. When the finished promise resolves, commitStyles writes the final opacity into the style, and cancel removes the animation. The box stays faded, and no animation is left on it.
Wait for finished before removing an element, so the animation is seen.
Checked in Chrome 156 only, by reading the finished promise and the final opacity. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
animate() takes keyframes and timing options.
The finished promise resolves at the end.
play, pause, reverse, cancel and playbackRate control playback.
commitStyles keeps the final values.
CSS is simpler for plain state changes.
Common mistakes
Expecting the end state to stay after the animation without fill or commitStyles.
Using setTimeout to guess when an animation ends instead of the finished promise.
Ignoring the reduced motion preference.
Follow-ups
What does commitStyles do?
How do you list the animations running on an element?
Tips
Name the Animation object and its finished promise.
Explain when you prefer WAAPI and when CSS is simpler.
169.html-css-0169Hardsenior
What is the View Transitions API, and how do you use it with a fallback?
document.startViewTransition(update) snapshots the old state, runs the update and animates to the new state. view-transition-name and the ::view-transition pseudo-elements customize it. It is newer, so check support, run the update directly where it is missing, and respect reduced motion.
Full answer
The View Transitions API animates between two states of the page with very little code. The browser takes a snapshot of the old state, runs your update, takes a snapshot of the new state, and cross-fades between them. You can then customize the animation with CSS.
The callback must change the DOM, and it can return a promise. The call returns a ViewTransition object with promises such as ready, updateCallbackDone and finished.
Customizing with CSS:
view-transition-name on an element gives it its own snapshot, so it can move or morph between positions. Names must be unique on the page at one time.
Pseudo-elements such as ::view-transition-old(name), ::view-transition-new(name) and ::view-transition-group(name) control the animation of each snapshot, with ordinary keyframes and timing.
The default cross-fade can be changed or removed for the whole page with ::view-transition-group(root).
Work for the same site across pages needs an extra opt-in with a rule for cross-document transitions, which is newer still.
Safety rules:
It is a newer feature, so check the support table. Always test if (!document.startViewTransition) and run the update directly. The page must work the same without the animation.
Respect reduced motion by disabling the animation inside @media (prefers-reduced-motion: reduce).
During the transition the page is not interactive, because input goes to a snapshot. Keep the duration short.
Do not give many elements names that are not needed, since each one makes a separate snapshot.
The box changes size on click. In a browser with the API, the change is animated from its old to its new snapshot. In a browser without it, the size changes at once, with the same final result.
The final state is the same in both cases, which is the test for a good fallback.
Checked in Chrome 156 only, where view transitions are available. A browser without them updates at once with no animation, and that case was not run. Check the support table. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
startViewTransition wraps a DOM update.
The browser animates between old and new snapshots.
view-transition-name and ::view-transition-* customize it.
Feature-test and keep the same final state without it.
Keep transitions short and honour reduced motion.
Common mistakes
Calling startViewTransition with no check for support.
Reusing the same view-transition-name on several visible elements.
Using long transitions, which block interaction.
Follow-ups
What does view-transition-name do?
Why can the page not be used during a long view transition?
Tips
Describe the snapshot idea in two sentences.
Say that the update must work with or without the API.
170.html-css-0170Hardsenior
How do you build a reading progress bar with scroll-driven animations, and what is the fallback?
A scroll-driven animation moves with scroll position. Use animation-timeline: scroll() for progress bars and view() for effects as an element crosses the viewport. Animate transform, wrap the rules in @supports, and make sure the page works without the effect.
Full answer
Normally a CSS animation moves forward with time. A scroll-driven animation moves with scroll position instead. When the user scrolls, the animation moves forward, and when they scroll back, it moves back. This replaces scroll event handlers for many effects.
There are two kinds of timeline.
A scroll progress timeline follows how far a scroll container has scrolled. animation-timeline: scroll() uses the nearest scroller, and scroll(root) uses the page. This suits a progress bar.
A view progress timeline follows how much an element has moved through its scroll container's view. animation-timeline: view() suits effects that run as an element enters or leaves the screen.
For a progress bar, define keyframes from scaleX(0) to scaleX(1), set animation-timing-function: linear, and attach the timeline. With a timeline, animation-duration is not used for the speed, so set it to auto or leave it. The animation-range property can limit which part of the scroll drives it.
Using transform keeps the animation cheap. The scroll-linked animation can run off the main thread in browsers that support it.
It is a newer feature, so check the support table. Plan the fallback:
Wrap the effect in @supports (animation-timeline: scroll()).
Outside that, the bar can stay hidden, or a small script can set the scale from scrollY on scroll with a passive listener. The page content must not depend on the effect.
Respect reduced motion. A progress bar is not strongly moving, but effects that fly elements around should be turned off in prefers-reduced-motion: reduce.
At the top of the page the bar has no width. Halfway down, it is half as wide as the window. At the bottom, it is full. In a browser without the feature, the bar stays at zero width, and the page still works.
The fallback here is only a hidden bar. A real page could add a scroll listener for those browsers.
Checked in Chrome 156 only, where scroll-driven animations are available. The bar width was read at the top, the middle and the bottom of the page. The fallback for other browsers was not run. Check the support table. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
Scroll-driven animations follow scroll position, not time.
scroll() tracks a scroller; view() tracks an element in view.
Animate transform and opacity.
Wrap in @supports and keep a fallback.
Respect reduced motion.
Common mistakes
Using scroll event handlers for effects that CSS can drive.
Animating layout properties with a scroll timeline.
Making content depend on the effect, so it fails where the feature is missing.
Follow-ups
What is the difference between scroll() and view()?
Why use transform for the bar?
Tips
Name the two timelines: scroll() and view().
Say that the effect must be a progressive enhancement behind @supports.
171.html-css-0171Mediummid
What is CSS Houdini, and which parts can you use today?
Houdini is a set of APIs that expose parts of the CSS engine. Custom property registration is the most usable part, Typed OM reads and writes styles as typed values, and the Paint API draws custom images but has limited support. Treat them as progressive enhancement.
Full answer
Houdini is a group of browser APIs that open up parts of the CSS engine to developers. Before it, the only way to extend CSS was a JavaScript library that worked around the browser. With Houdini, a script can hook into steps of styling and drawing.
The parts, by how much you can rely on them:
Custom property registration: @property in CSS or CSS.registerProperty() in script defines a type, a default and inheritance for a custom property, so it can be validated and animated. This is the most used part, and it is well supported in current browsers. Check the support table for your audience.
Typed OM: a way to read and write styles as typed values and not as strings. el.attributeStyleMap.set("width", CSS.px(120)) sets a width, and el.computedStyleMap().get("width").value reads a number. There are no string splits or unit parsing, and it can be faster. It is supported in Chromium based browsers, and support elsewhere varies.
Paint API: CSS.paintWorklet.addModule() loads a script that draws into a background or border image with a canvas-like context, which you then use as background: paint(name). It is mainly available in Chromium browsers, so a fallback background is needed.
Layout, Animation and Properties and Values worklets: more experimental, with limited or no support. Do not build features that depend on them.
Rules for use: treat Houdini features as progressive enhancement, test with CSS.supports() or by checking that the API exists, and keep a normal CSS fallback. A registered property with a fallback value is safe to use, while a paint worklet needs a plain background to show where it is not supported.
The Typed OM call sets a width of 120 pixels, and reading it back gives the number 120 with the unit px. The registered custom property shows its default of 8px. Whether the paint worklet exists depends on the browser.
Use Houdini where a fallback exists, and treat the rest as experiments.
Checked in Chrome 156 only. Houdini features have uneven support, so check the support table for each one. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
Houdini is a family of APIs, not one feature.
@property and registerProperty define typed custom properties.
Typed OM uses values such as CSS.px(120).
The Paint API has limited support and needs a fallback.
Feature-test before use.
Common mistakes
Building a feature on a worklet that only some browsers support, with no fallback.
Treating Houdini as one feature that is either supported or not.
Parsing style strings by hand when Typed OM could give numbers.
Follow-ups
What does registering a custom property add?
Why does the Paint API need a fallback?
Tips
Say that Houdini is a family of APIs with different levels of support.
Name @property, Typed OM and the Paint API.
172.html-css-0172Hardsenior
What are the trade-offs of CSS-in-JS, and how do runtime and build-time approaches differ?
Runtime CSS-in-JS builds and inserts CSS in the browser, which gives scoped, dynamic styles but costs JavaScript, render time and server rendering setup. Build-time tools extract plain CSS and pass dynamic values through custom properties. Choose by performance needs, framework and team habits.
Full answer
CSS-in-JS means writing styles in JavaScript files, next to the component that uses them. Libraries differ, but they fall into two groups.
Runtime libraries create the CSS in the browser. The component runs, the library turns its style object or template into CSS text, makes a unique class name, and inserts a style rule into the page. Styles can use props and state directly: color: ${props.color}.
Build-time (zero-runtime) tools extract the CSS during the build and ship normal CSS files. The class names are generated, and dynamic values are passed with custom properties, such as style="--color: red".
Benefits:
Styles live with the component, are removed with it, and cannot clash, because class names are unique.
Easy theming and dynamic values with JavaScript logic.
Typed styles and tooling in TypeScript projects.
Costs of the runtime kind:
Extra JavaScript to download and run, and work on every render: hashing, string building and rule insertion. This adds to the main thread time, especially with many dynamic styles.
Server rendering needs extra setup to collect the styles and send them with the HTML, or the page flashes without styles.
Many unique classes and rules from changing props can grow the style sheet and cause style recalculation.
Style insertion order can cause specificity surprises, and the generated names make debugging and global overrides harder.
It is harder to cache and to share one CSS file across pages and teams.
Build-time tools remove most of the runtime cost, but dynamic styles must be expressed through custom properties or a limited set of variants.
How to choose: consider the framework, the server rendering needs, the team's habits and performance budgets. Plain CSS with modules, custom properties and layers is a strong baseline that needs no runtime. Measure before deciding, and do not mix three methods in one codebase.
This tiny runtime caches by the rule text. The same style gives the same class and adds no new rule, while a different value adds one. Styles are applied through classes, and the rule count shows what a runtime has to grow.
A real library adds hashing, vendor handling and server rendering, which is where most of the cost and complexity come from.
html
<script>
const sheet = new CSSStyleSheet();
document.adoptedStyleSheets = [sheet];
const cache = new Map();
window.css = rules => {
if (!cache.has(rules)) {
const name = "c" + cache.size;
sheet.insertRule("." + name + " { " + rules + " }", sheet.cssRules.length);
cache.set(rules, name);
}
return cache.get(rules);
};
const a = css("color: rgb(10, 20, 30); padding: 4px");
const b = css("color: rgb(10, 20, 30); padding: 4px");
const c = css("color: rgb(200, 0, 0); padding: 4px");
document.body.insertAdjacentHTML("beforeend", '<p id="p1" class="' + a + '">One</p><p id="p2" class="' + c + '">Two</p>');
window.names = [a, b, c];
window.ruleCount = sheet.cssRules.length;
</script>
The library code is written by hand for the example. No CSS-in-JS package was installed or timed. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
Runtime libraries generate and insert rules in the browser.
Build-time tools ship extracted CSS.
Benefits: scoping, colocation and dynamic values.
Costs: JavaScript, server rendering and many rules.
Plain CSS with modules and custom properties is a strong baseline.
Common mistakes
Choosing a runtime library and ignoring server rendering and main thread cost.
Generating a new class for every prop value, which grows the style sheet.
Mixing several styling methods in one codebase.
Follow-ups
How do build-time tools handle dynamic values?
Why does server rendering need extra work with runtime CSS-in-JS?
Tips
Separate runtime and build-time libraries clearly.
List benefits and costs, and end with how you would choose.
173.html-css-0173Mediummid
How would you build a small utility class layer on top of design tokens without specificity problems?
Define tokens as custom properties, declare a layer order such as base, components, utilities, and write single-purpose classes in the last layer that use token values. Layer order lets utilities override components without !important, and a small scale keeps the set consistent.
Full answer
A utility class does one job, such as p-2 for padding or text-muted for a colour. A small set built on tokens gives speed without a large framework, and it can sit beside component styles.
Steps:
Define tokens as custom properties: a spacing scale --space-1: 4px, --space-2: 8px, and colours with names by role.
Declare the layer order once at the top: @layer reset, base, components, utilities;. Later layers win over earlier layers, whatever the specificity of the selectors, so utilities override components without !important and without long selectors.
Write each utility as one class with a single property and a token value: .p-2 { padding: var(--space-2); }. Keep the set small and consistent. Generate repetitive ones, such as a spacing scale, from a list.
Components set their normal look in the components layer, and the markup adds utilities for the exceptions.
Rules that keep it healthy:
Use utilities for layout and spacing exceptions, and keep component classes for repeated, meaningful parts. If the same ten utilities repeat across many places, make a component.
Do not add a utility for every possible value. A limited scale is the point.
Do not use !important inside utilities when layers are available.
Unlayered styles beat all layered styles, so keep third-party and old CSS in an early layer, or inside a named layer, to avoid surprises.
Document the scale so teams use the same names.
Compared with a full utility framework, a small layer gives less coverage, but it is easy to understand, needs no build step and uses the project's own tokens.
The first card has 16px padding from the component. The second has 8px padding and a muted colour, because the utilities layer comes after the components layer. The utility selectors have the same specificity as .card, and they still win by layer order.
Declare the order before any rules, so it does not depend on the order of the files.
Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
Tokens give utilities their values.
Layer order beats specificity.
Each utility does one thing from a limited scale.
Unlayered styles beat layered ones.
Repeated utility groups should become components.
Common mistakes
Adding !important to utilities when a layer order would solve the problem.
Creating a utility for every possible value instead of a limited scale.
Pasting the same long list of utilities everywhere instead of making a component.
Follow-ups
Why do unlayered styles beat layered ones?
When would you turn a group of utilities into a component?
Tips
Describe the three ingredients: tokens, a layer order and single-purpose classes.
Say why the utilities win without extra specificity.
174.html-css-0174Easyfresher
Work out which rule wins in six small cases, using the (id, class, element) count.
Count ids, classes and elements as three numbers and compare from left to right. Equal scores are decided by source order. The argument of :not() counts, :where() adds zero, inline styles beat selectors, and an important stylesheet rule beats a normal inline style.
Full answer
Specificity is a score written as three numbers: ids, then classes (with attributes and pseudo-classes), then elements (with pseudo-elements). Compare the first number first, then the second, then the third. A bigger earlier number always wins, whatever the later numbers are. If the scores are equal, the later rule in the source wins. Inline styles beat any selector, and !important in a stylesheet beats a normal inline style.
Six cases, with the answer for each:
p { color: red } is (0,0,1) and .note { color: blue } is (0,1,0). Class beats element, so the text is blue.
div.m is (0,1,1) and .m.n is (0,2,0). Two classes beat one class and one element, so the winner is the second rule, orange.
#e3 is (1,0,0) and a selector with eleven classes is (0,11,0). One id beats any number of classes, so purple wins. The numbers do not carry over.
section:not(#zzz) counts the id inside :not(), so it is (1,0,1). It beats .r at (0,1,0), even though the id does not exist. The winner is brown.
Two rules with the same selector .s have equal scores, so the later one wins, navy.
An inline style="color: black" beats #e6 { color: red }. But #e7 { color: red !important } beats an inline style without !important.
Other points: the universal selector * and combinators add nothing. :is() takes its strongest argument, and :where() adds zero. Pseudo-elements count as elements. Check the number with the browser tools, which show the winning rule.
The browser colours match the answers above: blue, orange, purple, brown, navy, black and red.
Do the counting by hand first, and then check in the browser tools.
Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
Specificity is (ids, classes, elements), compared left to right.
One id beats any number of classes.
Equal scores: the later rule wins.
:not() and :is() count their strongest argument; :where() counts zero.
Inline beats selectors; !important in a stylesheet beats normal inline.
Common mistakes
Thinking that eleven classes beat one id.
Forgetting that the argument of :not() counts.
Forgetting that source order only matters when scores are equal.
Follow-ups
What is the specificity of :where(#a) p?
Does the universal selector add specificity?
Tips
Say how to compare: left to right, the first difference decides.
Work one example aloud, such as the :not(#id) case.
175.html-css-0175Hardsenior
How would you plan a migration from a large legacy stylesheet to a cleaner structure without a rewrite?
Measure the current state, add visual tests, put legacy CSS in a low layer so new rules win without specificity fights, add tokens, migrate component by component, block new bad patterns with linting, and remove dead code while tracking the numbers.
Full answer
A full rewrite of a large stylesheet is slow and risky, because nothing ships until it is finished, and the visual differences are hard to find. An incremental plan keeps the site working at every step.
A practical plan:
Measure first. Collect the size, the number of rules, unused rules, the highest specificity values and the count of !important. Use the coverage tool in the browser and a script over document.styleSheets. Write down the goals, for example fewer overrides and smaller files.
Protect the look. Add visual regression tests for the most important pages and components before changing anything, so every step can be compared.
Contain the legacy code. Put the old CSS into a low layer, for example @layer legacy. Because layer order beats specificity, new rules in a later layer win over old rules that use long, strong selectors, with no !important. Declare the layer order once at the top.
Introduce tokens. Add custom properties for colours, spacing and type, and let new components use them. Old rules can start reading tokens too, one at a time.
Migrate by component. Pick one component, write it in a new layer, switch the markup to use it, check the visual tests, and delete the old rules for it. Start with the most reused and the most painful parts.
Stop the flow of new problems. Add a linter, a rule that forbids ids in selectors and !important, and a review rule that new code goes into the new layers.
Remove dead code regularly, and track the numbers from step 1.
Risks to plan for:
Unlayered CSS beats all layered CSS. The old CSS must be moved into a layer, or be the only unlayered CSS on purpose. A third-party stylesheet that is not layered can also win, so wrap it with @import url() layer(vendor) or a @layer block.
Rules inside a layer keep their own specificity battles, so a very strong legacy rule still beats a weak legacy rule in the same layer.
!important reverses the layer order, so an important rule in legacy beats an important rule in a later layer.
In the first case, the old rule is more specific, but it is in the earlier layer, so the new blue rule wins. In the second case, the old rule is not in any layer, so it beats the layered component and the button stays gray. This is why step 3 matters.
Report progress with numbers, so the team can see the migration working.
Checked in Chrome 156 only. No real legacy stylesheet or visual regression tool was run. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
Do not rewrite everything at once.
Measure and add visual tests first.
Put legacy CSS in a low layer; new layers win.
Migrate one component at a time and delete the old rules.
Prevent new problems with linting and review rules.
Common mistakes
Starting a full rewrite with no visual tests.
Leaving legacy CSS unlayered, so it beats the new layers.
Not stopping new legacy-style code during the migration.
Follow-ups
Why does unlayered CSS beat layered CSS?
How do you measure progress?
Tips
Give the steps in order: measure, protect, contain, tokens, migrate, prevent, remove.
Explain why the layer for legacy code makes the migration safe.
176.html-css-0176Hardsenior
How would you audit a stylesheet for unused rules and risky patterns, and what are the limits of a script?
Measure size, rule counts, unused rules, strong selectors and !important with the coverage panel and a CSSOM script. The output is a list of candidates only, because rules can be used in other states, pages or dynamic cases, and cross-origin sheets cannot be read.
Full answer
An audit gives numbers and a list of problems. The sources are the browser tools and a small script over the CSS Object Model (CSSOM).
What to look for:
Size and count: bytes sent, number of rules and number of selectors.
Unused rules: selectors that match nothing on the pages you checked. The coverage panel in the browser tools shows the used and unused bytes for a page load.
Duplicates and overrides: the same property set again and again for one selector, or by many selectors.
Strong selectors: ids, deep descendant chains and many classes, which cause specificity fights.
!important: the number of uses, and where they are.
Inline styles in the HTML, and vendor prefixes that are no longer needed.
A script can read document.styleSheets, loop over cssRules and test each selector with document.querySelector(). Treat the output as a list of candidates, not as a list of things to delete.
Limits:
A selector that matches nothing now may match after a click, in another state, on another page, or for another user. State pseudo-classes such as :hover cannot be tested by querySelector, so strip them or skip them.
The script sees one page. Combine results from many pages, and from the real site traffic if possible.
Cross-origin style sheets cannot be read, because the browser blocks access to their rules.
Rules in @media and @layer blocks need a recursive walk.
Dynamic class names, built by JavaScript, will look unused.
Before deleting anything, check the candidate rules in a test build with visual tests.
The report finds five rules from the style element. It lists .ghost, #nope and .also-ghost as unused. It does not list a:hover, because the state is removed first. It counts one !important. These are the candidates to look at, and a person must still decide.
The page is read once. Run the same check on many pages before trusting the list.
html
<style>
.used { color: rgb(10, 20, 30); }
.ghost { color: red !important; }
#nope { margin: 0; }
a:hover { text-decoration: underline; }
@media (min-width: 400px) { .also-ghost { padding: 1px; } }
</style>
<p class="used">Used</p><a href="#">Link</a>
<script>
const report = { rules: 0, unused: [], important: 0 };
const stateless = s => s.replace(/:(hover|focus|active|visited|focus-visible|focus-within)\b/g, "");
function walk(rules) {
for (const rule of rules) {
if (rule.cssRules && !rule.selectorText) { walk(rule.cssRules); continue; }
if (!rule.selectorText) continue;
report.rules++;
if (!document.querySelector(stateless(rule.selectorText))) report.unused.push(rule.selectorText);
for (const p of rule.style) if (rule.style.getPropertyPriority(p) === "important") report.important++;
}
}
for (const sheet of [...document.styleSheets]) { try { walk(sheet.cssRules); } catch (e) {} }
window.report = report;
</script>
The script was run on this one test page in Chrome 156. Real sites need many pages and states. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
Use coverage and a CSSOM script.
Measure size, unused rules, specificity and !important.
Strip state pseudo-classes before testing selectors.
Combine results from many pages and states.
Verify before deleting.
Common mistakes
Deleting every rule that a script reports as unused.
Testing only one page and one state.
Forgetting that dynamic class names look unused.
Follow-ups
Why can :hover rules not be tested with querySelector?
Why can a script not read some stylesheets?
Tips
List what you measure, then the tools, then the limits.
Say that a script gives candidates, and humans check them.
177.html-css-0177Hardsenior
How would you roll out a design system to several teams so that people actually adopt it?
Audit existing patterns, ship tokens first, then a small set of accessible components with a stable attribute-based API in a layer. Roll out gradually, version with a migration path, document, add a contribution process, test visually and measure adoption.
Full answer
A design system is a set of tokens, components, rules and documentation that teams share. The hard part is not building it but getting it used and kept up to date. A rollout plan covers both the code and the people.
Foundation:
Start with an audit of the current products to find the real, repeated patterns. Build the system from what teams use, and not from an ideal design.
Ship tokens first. Colours, spacing and type are the cheapest to adopt and give quick visual consistency.
Build a small set of components that cover most screens: button, input, form field, card, dialog and navigation. Make them accessible by default, with keyboard support, focus styles and correct roles, so teams do not need to solve it again.
Component design:
A small, stable API. Variants through attributes or props, such as data-variant="primary" and data-size="lg", and defaults for everything. Avoid many one-off options.
Styles in a layer, using tokens, so that products can override with a simple rule.
No dependency on page-global styles.
Escape hatches that are documented, such as custom properties for the few things that teams may change.
Rollout and governance:
Version it with semantic versions and a change log. Breaking changes need a migration path, codemods if possible, and a deprecation period with warnings.
Documentation with live examples, usage rules and accessibility notes.
A contribution process: how a team proposes a new component or a change, and who decides. Provide a way to ask questions, such as a channel and office hours.
Adoption is gradual. Start with one product and one friendly team, use their feedback, and then widen. Let teams adopt component by component.
Measure: share of components from the system, number of overrides, accessibility bugs, and time to build a screen. Use the data to decide what to improve.
Add tests: visual regression for components and automated accessibility checks.
The default button uses the action colour. The second button changes variant and size through attributes, and the component keeps its own focus style. A product that wants a different look can override the tokens or add a rule in a later layer.
Treat the system as a product with users, a roadmap and support.
Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
Audit first, and build from real patterns.
Tokens first, then a few accessible components.
Stable API: variants as attributes, styles in a layer.
Semantic versions, deprecation and migration paths.
Docs, governance, tests and adoption metrics.
Common mistakes
Building a large system before any team uses it.
Making breaking changes with no migration path.
Measuring nothing, so no one knows whether it helps.
Follow-ups
Why ship tokens before components?
How do you handle a breaking change?
Tips
Separate the code (tokens, components) from the people part (versions, docs, governance, metrics).
Describe a stable component API with variants and layers.
178.html-css-0178Hardsenior
How do you test CSS in a project, and what can each kind of test catch?
Combine linting for source rules, computed style tests for exact values and states, visual regression for unplanned changes, automated accessibility checks plus manual testing, and checks across widths and modes. Keep the tests stable and few enough to trust.
Full answer
CSS is hard to test because the output is a picture, and small changes can have large side effects. A good strategy combines several kinds of test, each with its own job.
Linting. A tool such as Stylelint reads the source and catches syntax errors, unknown properties, duplicate selectors, !important, ids in selectors and style rules that break your conventions. It is fast and runs in the editor and in the CI pipeline. It cannot see the result.
Computed style tests. In a real browser, load a component and assert values: the colour of a button, the padding, the display type, the position. They are quick and precise, and they work well for tokens and states, such as focus or hover, and for media queries by changing the viewport. They do not catch a layout that looks wrong when all numbers are right.
Visual regression tests. Take a screenshot of each component or page, compare it with an approved baseline and fail when the difference is above a small threshold. They catch unplanned changes, such as a header that moved 10 pixels. Cost: baselines need review when a change is intended, fonts and rendering must be the same in every run (use one browser version in a container), and animation and dynamic data must be frozen.
Accessibility checks. Automated tools find missing names, low contrast and invalid ARIA in the rendered page. They catch many but not all problems, so also test with the keyboard and a screen reader by hand.
Responsive and state coverage. Run the tests at several widths, in dark mode, with reduced motion, with forced colours and with larger text.
Performance budgets. Track the size of the stylesheet and the time of style and layout work for key pages.
A good order: lint on every change, computed and accessibility tests on every pull request, and visual tests on components with a review step. Keep tests few and meaningful, because slow or flaky tests are ignored.
Three assertions pass. The fourth fails on purpose, because the button has the default border of 2px, and the failure message shows the real value. This is the kind of unplanned default that computed tests find.
Choose tests by the risk, and keep each one stable enough to trust.
The test helper is a small stand-in written for the example. No Stylelint, screenshot or accessibility tool was run. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
Linting checks the source, not the result.
Computed style tests check exact values in a browser.
Automated accessibility checks find many but not all issues.
Test several widths and modes; keep tests stable.
Common mistakes
Using only screenshot tests, with unstable fonts and dynamic data.
Testing numbers only, and missing layouts that look wrong.
Writing so many tests that the team ignores failures.
Follow-ups
What makes visual regression tests flaky?
Why are automated accessibility checks not enough?
Tips
Name the test types and what each catches and misses.
Give a sensible order for a pipeline.
179.html-css-0179Mediummid
What edge cases should you know about the details element, beyond opening and closing?
The open attribute is the state, and the toggle event fires asynchronously after changes by user or script. summary should not contain interactive content, closed content is not rendered, so animation needs a different technique, and find-in-page and print behaviour must be tested.
Full answer
Basic use of details is easy, but some behaviours surprise people.
The first child that matters is summary. If there is no summary, the browser makes a default label such as "Details". Only the first summary child is used as the label.
The content of summary is treated as phrasing content. Putting a heading in it is allowed in current HTML, but it changes how assistive tools announce it, and interactive elements such as a link or a button inside a summary are a poor idea because the whole summary is already a button.
State: the open attribute is the state. Setting details.open = true from a script opens it, and removing the attribute closes it. The toggle event fires after the state changes and is asynchronous, so it can fire later than the code that set open. It fires for changes by the user and by script. A beforetoggle event exists in newer browsers for popovers and dialogs, but not for details.
Keyboard: summary is focusable and Enter or Space toggles it.
Find in page: in current Chromium browsers, text inside a closed details can be found by the browser's search, and the details opens to show the match. Support differs by browser, so do not rely on it for important content.
Hiding the arrow: use summary { list-style: none; }, or summary::marker { content: ""; }, and draw your own indicator with CSS using details[open]. Keep a clear sign that the element can be opened.
Animation: the hidden content is not rendered, so a simple height transition does not run. The grid row technique or the newer pseudo-element for the content part can help, but check the support table.
Nesting is allowed, and each details keeps its own state. The name attribute groups elements so that only one is open in supported browsers.
Printing: closed content is normally not printed. Open the elements for print with a script on beforeprint if all content should appear.
Closed, the paragraph takes no space. A click on the summary opens it and fires one toggle event. Pressing Enter on the focused summary also toggles it. The plus sign changes to a minus without any script.
Test the find-in-page and printing behaviour in the browsers you support.
Checked with a mouse click and a real Enter key press in Chrome. Find in page and printing were not tested. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
Only the first summary is the label.
open is the state; toggle is asynchronous.
Do not put links or buttons in summary.
Closed content is not rendered, so height transitions need another technique.
Test find-in-page and print.
Common mistakes
Putting links or buttons inside summary.
Expecting the toggle event to fire synchronously after setting open.
Hiding the marker and leaving no sign that the content can be opened.
Follow-ups
Is the toggle event synchronous?
How do you show all details content in print?
Tips
Pick three or four edge cases: toggle timing, find in page, animation, print.
Mention that the whole summary acts as a button.
180.html-css-0180Hardsenior
Build a header, a left menu, main content, a right sidebar and a footer that stays at the bottom. How do you keep the HTML order sensible?
Write the HTML in a sensible reading order, make body a grid with named areas, columns of fixed side widths and a fluid centre, and rows auto, 1fr and auto so the footer stays at the bottom. Stack the areas in a media query for small screens.
Full answer
The holy grail layout has a header, three columns (menu, main content and side content) and a footer. The old challenge was equal height columns, a fluid centre and content that comes first in the HTML, using floats. With Grid, it is short.
Steps:
Write the HTML in a reading order that makes sense: a skip link, header, nav, main, aside, footer. Keyboard and screen reader users follow this order, so the order should be the one a person would expect.
Make body a grid with min-height: 100vh (and 100dvh after it). Name the areas: header across the top, nav, main and aside in the middle, footer across the bottom.
Use grid-template-columns: 160px 1fr 160px so the centre is fluid, and grid-template-rows: auto 1fr auto. The 1fr row takes the free space, so the footer is pushed to the bottom of the window on short pages and moves down on long pages. The columns stretch, so they have equal height with no extra tricks.
Make it responsive. Below a breakpoint, use one column with areas in the order of the HTML. On narrow screens, the menu may become a button menu.
Add min-width: 0 or use minmax(0, 1fr) for the centre, so long content cannot widen the grid.
If the content must come before the menu in the HTML, for example for a long navigation, use a skip link, and keep the visual order close to the source order. Large differences between visual and source order harm keyboard users.
An older version of the same layout uses Flexbox: a column flex body with flex: 1 on a middle row that is itself a row flex container. Both work. Grid is clearer here because the layout is two-dimensional.
On a wide window, the menu is on the left, the main content is in the middle with the rest of the width, and the sidebar is on the right. The footer touches the bottom of the window even with little content. Below 600 pixels, everything stacks in the HTML order.
Test with long content, and with the keyboard, to confirm that the focus order matches what you see.
html
<style>
body { margin: 0; min-height: 100vh; min-height: 100dvh; display: grid; font-family: sans-serif;
grid-template-columns: 160px minmax(0, 1fr) 160px;
grid-template-rows: auto 1fr auto;
grid-template-areas: "h h h" "n m a" "f f f"; }
header { grid-area: h; background: #cde; }
nav { grid-area: n; background: #fdc; }
main { grid-area: m; }
aside { grid-area: a; background: #dfc; }
footer { grid-area: f; background: #333; color: #fff; }
.skip { position: absolute; left: 8px; top: -3em; }
.skip:focus { top: 8px; }
@media (max-width: 600px) {
body { grid-template-columns: minmax(0, 1fr); grid-template-areas: "h" "n" "m" "a" "f"; grid-template-rows: auto; }
}
</style>
<a href="#main" class="skip" id="skip">Skip to content</a>
<header id="h">Header</header>
<nav id="n">Menu</nav>
<main id="main"><p>Short content</p></main>
<aside id="a">Side</aside>
<footer id="f">Footer</footer>
Checked at a width of 800 pixels and at 400 pixels in Chrome. The focus order was not tested with a screen reader. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
HTML order should match the reading and focus order.
grid-template-areas names header, nav, main, aside and footer.
Rows auto, 1fr and auto give a sticky footer.
Columns stretch, so they have equal height.
Stack areas on small screens.
Common mistakes
Using floats and clearfix hacks for this layout today.
Placing content first in the HTML and the menu first on screen with no skip link.
Forgetting min-height or the 1fr row, so the footer floats in the middle of the screen.
Follow-ups
Why does the centre column use minmax(0, 1fr)?
How does the layout change on a phone?
Tips
Say that the HTML reading order comes first, and the grid areas follow.
Explain how rows auto, 1fr and auto give the sticky footer.