← Interview prep

HTML & CSS interview questions

Semantic HTML, CSS layout, and CSS interview depth.

193 questions · Page 5 of 10

Want the full pack? Interview packs · Mock interview · Mentora

Page 5 of 10

Questions 81–100 of 193 · 0 of 20 on this page marked learned

81.html-css-0081Hardsenior

What does the popover attribute give you, and how is it different from building a tooltip or menu with CSS and JavaScript?

The popover attribute plus popovertarget shows an element in the top layer with light dismiss and Escape handling, with no script. It does not make the page inert and does not position itself, so use dialog for modals. It is newer, so check support and provide a fallback.

Full answer

The popover API lets HTML show an element on top of the page without writing the show and hide code yourself. You add the popover attribute to an element, and give a button popovertarget="id" pointing at it. Clicking the button toggles the popover.

What the browser handles:

  • Top layer: the popover is drawn above other content, so you do not fight z-index or overflow: hidden on parents.
  • Light dismiss: with popover (the same as popover="auto"), pressing Escape or clicking outside closes it, and opening one auto popover closes other unrelated ones.
  • Focus and keyboard: Escape closes it, and focus returns to the invoker in typical cases.
  • Relations: the invoking button gets expanded state semantics for assistive technology in browsers that support the feature.
  • popover="manual" turns off light dismiss, so you decide when to close it. Useful for toasts.

Styling hooks: the :popover-open pseudo-class matches while it is shown. Before it is shown, the element is display: none. The ::backdrop pseudo-element exists for popovers too, but only a dialog opened with showModal() makes the page behind inert. A popover does not. Use dialog for real modals.

JavaScript can still help: showPopover(), hidePopover(), togglePopover() and the toggle event.

The popover is a newer feature, so check the support table, and keep a plain fallback for important content. Positioning near the button is not automatic. CSS anchor positioning can do it, or you can place it by hand.

Clicking Info shows the box above everything else, and a second click hides it. Pressing Escape also closes it. Clicking elsewhere closes it too.

Where the attribute is not supported, the element is simply shown as normal content, unless you hide it with a feature check, so test your fallback.

html
<style>
  [popover] { border: 1px solid #999; padding: 8px; margin: 0; }
  #tip { position: fixed; top: 60px; left: 20px; }
  #tip:popover-open { background: #ffd; }
</style>
<button id="open" popovertarget="tip" type="button">Info</button>
<div id="tip" popover>Fees are paid every month.</div>
<button id="other" type="button">Other</button>

Checked in Chrome 156 only, by clicking, pressing Escape and clicking outside. Other browsers 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

  • popover and popovertarget toggle an element with no script.
  • The top layer avoids z-index and overflow problems.
  • Auto popovers close on Escape and outside clicks; manual ones do not.
  • :popover-open styles the open state.
  • A popover is not modal; use dialog with showModal() for modals.

Common mistakes

  • Using popover for a modal and expecting the background to become inert. Use dialog with showModal().
  • Using popover="manual" for a menu and forgetting to close it on Escape or outside click.
  • Assuming the popover is placed beside its button automatically.

Follow-ups

  • How does popover="manual" differ from the default?
  • Which pseudo-class matches an open popover?

Tips

  • Say what the browser provides: top layer, light dismiss, Escape and focus handling.
  • Compare it with dialog, and say where each fits.
82.html-css-0082Hardsenior

How would you place a tooltip next to its button with CSS anchor positioning, and what is the fallback?

Give the button an anchor-name, set position-anchor on a fixed or absolute element, and place it with anchor() or position-area. Add position-try-fallbacks for edge cases and wrap everything in @supports, since the feature is newer and needs a simple fallback.

Full answer

Before anchor positioning, placing a box next to another box meant a wrapper with position: relative, or JavaScript that measured the button and set top and left. Both break when the button moves, or when the box would run off the screen.

CSS anchor positioning connects two elements in CSS.

  1. Name the anchor: anchor-name: --info on the button.
  2. Link the positioned element: position-anchor: --info. It must be absolutely or fixed positioned.
  3. Place it with anchor() in inset properties, for example top: anchor(bottom) and left: anchor(left), or with the shorter position-area.
  4. Optionally add position-try-fallbacks so the browser flips the box to another side if it would overflow the screen.

Anchor positioning is a newer feature. Check the support table. Write a fallback first and then override it inside @supports (anchor-name: --a). The fallback can be simple, such as a box placed under a position: relative wrapper with fixed offsets.

It pairs well with the popover attribute. A popover is in the top layer, so it escapes overflow: hidden, and anchoring places it near the invoker.

In a browser with anchor positioning, the tip opens just under the Info button, left edges aligned, and it moves to the top of the button if there is no space below. Elsewhere, the fallback rules apply, which may place the box less precisely. Test the fallback by temporarily removing the @supports block.

Keep the feature as an enhancement. The page should still work if the box is only roughly placed.

html
<style>
  body { font-family: sans-serif; }
  .wrap { position: relative; display: inline-block; margin: 40px; }
  #tip {
    position: absolute; inset: auto; top: 100%; left: 0;
    margin: 4px 0 0; padding: 6px 8px; border: 1px solid #999; background: #ffd;
  }
  @supports (anchor-name: --a) {
    #info { anchor-name: --info; }
    #tip {
      position: fixed;
      position-anchor: --info;
      top: anchor(bottom);
      left: anchor(left);
      position-try-fallbacks: flip-block;
      margin: 4px 0 0;
    }
  }
</style>
<div class="wrap">
  <button id="info" popovertarget="tip" type="button">Info</button>
  <div id="tip" popover>Fees are paid every month.</div>
</div>

Checked in Chrome 156 only, where anchor positioning is available. The fallback rules were not run in a browser without it. 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

  • anchor-name defines the anchor; position-anchor links to it.
  • anchor() in top, left and similar properties places the box.
  • position-try-fallbacks flips the box when space runs out.
  • Wrap it in @supports with a plain fallback.
  • It pairs well with popover, which uses the top layer.

Common mistakes

  • Using anchor positioning with no fallback or support check.
  • Forgetting that the positioned element must be absolute or fixed.
  • Using one anchor-name for many buttons on the page without thinking about which one the tooltip links to.

Follow-ups

  • Why is a popover a good partner for anchor positioning?
  • What does position-try-fallbacks do?

Tips

  • Describe the three steps: name, link, place.
  • Mention position-try-fallbacks as the answer to overflow near the viewport edge.
83.html-css-0083Hardsenior

Compare BEM, utility-first CSS and CSS Modules. How would you choose for a team project?

BEM is a naming rule with flat selectors, utility-first uses small single-purpose classes, and CSS Modules makes class names local through a build step. Choose by team size, framework and tooling, and use custom properties for tokens and @layer for ordering in any of them.

Full answer

All three try to solve the same problem: global CSS is shared by every page, so a change in one place can break another place.

BEM (Block, Element, Modifier) is a naming rule. A block is a standalone part such as card. An element is a part of it, written card__title. A modifier is a variant, written card--featured. Every selector is one class, so specificity stays flat and low, and the name tells you where the style belongs. Cost: long names, and discipline is needed because nothing in the tools enforces it.

Utility-first CSS uses many small single-purpose classes such as p-4, flex and text-center, put straight in the HTML. Styles are not named after the content, and the CSS file stops growing after a while. Cost: long class lists in markup, and a need to extract repeated patterns into components. A build step usually removes unused utilities.

CSS Modules gives each CSS file local class names. The build tool renames .title to something unique such as card_title_x7k2, so classes cannot clash across files. You write normal CSS and import it into the component. Cost: needs a bundler, and global theming still needs custom properties or a shared layer.

How to choose:

  • Many contributors and a component framework: CSS Modules or a utility system keep scope under control.
  • Content sites with plain templates and no build step: BEM works with nothing but discipline.
  • Design system with tokens: use custom properties for the tokens in all three.

Combine with other tools. @layer can order resets, base, components and utilities, so utilities win without !important. Tokens in custom properties are shared across any method.

The BEM card has a blue border, and each selector is a single class, so the specificity is 0,1,0 for all of them. The utility box gets padding and centred text from two classes. The last class stands for what a CSS Modules build would generate from .title.

The class name in the last line is written by hand for the example. A real build tool creates it.

html
<style>
  .card { border: 1px solid #999; padding: 8px; }
  .card__title { margin: 0; font-size: 18px; }
  .card--featured { border-color: #0a6cff; }
  .p-4 { padding: 16px; }
  .text-center { text-align: center; }
  .card_title_x7k2 { color: teal; }
</style>
<div class="card card--featured" id="bem">
  <h3 class="card__title" id="bemt">BEM card</h3>
</div>
<div class="p-4 text-center" id="util">Utility classes</div>
<h3 class="card_title_x7k2" id="mod">Module-style generated name</h3>

The generated-looking class name is written by hand. No build 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

  • BEM uses block, element and modifier names with single-class selectors.
  • Utility-first puts small single-purpose classes in the markup.
  • CSS Modules renames classes per file at build time.
  • Choose based on team, framework and build setup.
  • Tokens and @layer work with all three.

Common mistakes

  • Choosing a method for style and not for team size and build setup.
  • Mixing BEM names with deep selectors like .card .card__title a, which defeats the flat specificity.
  • Using utilities without extracting repeated patterns into components, so the same ten classes are pasted everywhere.

Follow-ups

  • How can @layer help when utilities need to win over component styles?
  • What does a CSS Modules build do to a class name?

Tips

  • Say what each one solves: naming, repetition or scope.
  • Add that tokens and @layer work with all three.
84.html-css-0084Hardsenior

What does will-change do, and why is overusing it a problem?

will-change tells the browser which property will change so it can prepare, often by creating a compositor layer. It costs memory and can create a stacking context and containing block, so use it sparingly on transform or opacity, add it just before animating, and remove it afterwards.

Full answer

will-change tells the browser which property of an element is likely to change soon, for example will-change: transform. The browser can prepare ahead of time, usually by moving the element to its own compositor layer. Animations of transform and opacity can then run on the compositor without repainting the page on every frame.

It is a hint and not a speed switch. Using it has costs:

  • Each layer uses graphics memory. Many layers on a phone can slow things down or crash a tab.
  • It can create a stacking context and a containing block, depending on the property. will-change: transform makes the element the containing block for fixed descendants, just like a real transform does. This can break a fixed menu inside it.
  • The browser may drop its own optimizations for elements that you did not need to hint.

Good practice:

  1. Do not add it by default or with *. Use it only after measuring a real jank problem.
  2. Add it just before the change, and remove it afterwards. In CSS, a rule on :hover of the parent can warm up the child. In JavaScript, set it on mouseenter and clear it when the animation ends.
  3. Hint only properties that are cheap to animate: transform and opacity. Animating width, top or box-shadow still triggers layout or paint, and will-change does not remove that.
  4. Do not hint a property that will not animate.

Many animations are already optimized by the browser, so a simple transition: transform is often enough.

The card has no hint at first. When the pointer enters the list, will-change: transform is added, and the card moves up 4px when hovered. The red fixed square inside the hinted box is placed relative to that box, not to the window, which shows the containing block side effect.

Check the result in the DevTools layers or performance panel. Remove the hint if you see no gain.

html
<style>
  body { margin: 0; font-family: sans-serif; }
  .card { width: 100px; height: 60px; background: #cde; transition: transform 0.2s; }
  .list:hover .card { will-change: transform; }
  .card:hover { transform: translateY(-4px); }
  .hinted { will-change: transform; height: 100px; background: #eee; }
  .hinted .fixed { position: fixed; top: 0; left: 0; width: 30px; height: 30px; background: tomato; }
  .spacer { height: 120px; }
</style>
<div class="spacer"></div>
<div class="list" id="list"><div class="card" id="card">Card</div></div>
<div class="hinted" id="hint"><div class="fixed" id="fx"></div></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

  • will-change is a hint to the browser, not a guaranteed speed-up.
  • It often creates a compositor layer, which costs memory.
  • will-change: transform makes the element a containing block for fixed descendants.
  • Apply it briefly, to transform or opacity, after measuring a problem.
  • Layout properties still cause layout or paint when animated.

Common mistakes

  • Setting will-change on many elements in a global rule, which wastes memory.
  • Leaving will-change set permanently after the animation ends.
  • Expecting will-change to speed up animations of layout properties like width or top.

Follow-ups

  • Why are transform and opacity cheap to animate?
  • How would you add and remove will-change from JavaScript?

Tips

  • Say that it is a hint with a memory cost. Show that you would measure first.
  • Mention the fixed descendant side effect. It is a real bug source.
85.html-css-0085Hardsenior

A page has an unwanted horizontal scrollbar on phones. How do you find the cause and fix it properly?

Find the element that is wider than the viewport with DevTools or a console check, then fix the cause: fixed pixel widths, 100vw, long unbroken text, wide media or flex items with min-width: auto. Do not hide the symptom with overflow-x: hidden on the body.

Full answer

A horizontal scrollbar means something is wider than the viewport. Hiding it with overflow-x: hidden on body is a patch that hides the symptom, can break position: sticky, and can cut off content that users should see. Find the element first.

Steps to find it:

  1. Open DevTools in a narrow viewport. Scroll right and see which part sticks out.
  2. Run a short check in the console that lists elements whose right edge is past the viewport width: compare el.getBoundingClientRect().right with document.documentElement.clientWidth.
  3. Or add a temporary * { outline: 1px solid red; } and look for the box that reaches beyond the edge.

Frequent causes and fixes:

  • A fixed width in pixels such as width: 600px. Use max-width: 100% or a fluid width.
  • width: 100vw with a vertical scrollbar present. 100vw includes the scrollbar width, so it is wider than the visible area on desktop browsers that show classic scrollbars. Use width: 100% instead.
  • A long word, URL or code line. Use overflow-wrap: anywhere on text, or overflow-x: auto on a pre.
  • A wide table or image. Give images max-width: 100% and put tables in a scrollable wrapper.
  • A flex item that refuses to shrink because of min-width: auto. Add min-width: 0.
  • Negative margins, or padding added to a width: 100% box without box-sizing: border-box.

The first green block is 500px wide inside a 300px box, so the box has a horizontal scroll width. The second is limited to 100% of the box. The first long address is wider than its box, and the second wraps inside it. Compare scrollWidth and clientWidth to see the difference.

After the fix, test the real page at 320px width and with browser zoom, and look for new clipping.

html
<style>
  html, body { margin: 0; }
  * { box-sizing: border-box; }
  .fixed { width: 500px; background: #cfc; }
  .fixed.fixed-ok { width: 100%; max-width: 500px; }
  .url { background: #cde; }
  .url.url-ok { overflow-wrap: anywhere; }
</style>
<div style="width:300px;overflow:auto;height:60px" id="box">
  <div class="fixed" id="a">Fixed 500px</div>
  <div class="fixed fixed-ok" id="b">Fluid</div>
  <div class="url" id="c">https://example.com/a/very/long/address/without/any/break/points/in/it</div>
  <div class="url url-ok" id="d">https://example.com/a/very/long/address/without/any/break/points/in/it</div>
</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

  • Locate the overflowing element before changing anything.
  • Fixed widths, 100vw and long strings are common causes.
  • Flex items may need min-width: 0.
  • overflow-x: hidden on body only hides the symptom.
  • Retest at 320px and with zoom.

Common mistakes

  • Adding overflow-x: hidden to the body without finding the element that is too wide.
  • Using 100vw for full-width blocks, which includes the scrollbar width.
  • Fixing the width of one element but not checking again at other screen sizes and zoom levels.

Follow-ups

  • Why can 100vw cause a horizontal scrollbar?
  • How would you list the elements that are wider than the viewport in the console?

Tips

  • Describe a method, not a guess: find the element first with the console, then fix the cause.
  • Name 100vw and min-width: auto as two causes that surprise people.
86.html-css-0086Easyfresher

Which image format would you pick for a photo, a logo and a screenshot, and how do you offer a fallback?

Use JPEG, WebP or AVIF for photos, PNG or WebP for sharp images that need transparency, and SVG for logos and icons. Offer newer formats with picture and source type, and keep a JPEG or PNG img as the fallback.

Full answer

Each format suits a different kind of picture.

  • JPEG is good for photos. It is small, but it loses detail, and it has no transparency.
  • PNG is good for screenshots, text and images with sharp edges, and it supports transparency. Photos in PNG are large.
  • SVG is a drawing described in text. It stays sharp at any size, which suits logos, icons and simple illustrations. It is a poor choice for photos.
  • WebP and AVIF are newer formats. They are often smaller than JPEG or PNG at similar quality, and they support transparency. AVIF is often the smallest but can be slower to create. Check the support table for your visitors.
  • GIF is old and large. Use a short video or an animated WebP for animations.

To offer a newer format with a safe fallback, use picture with several source elements. The browser takes the first source whose type it understands. The img at the end is the fallback, and it also carries the alt text and the size.

A browser that understands AVIF loads the AVIF file. One that knows only WebP loads the WebP file. All others load the JPEG. The page keeps one alt text and one reserved size for all cases.

Always give width and height so the page does not jump when the image loads. Size the image to the largest size it is shown at, and compress it before upload.

html
<picture>
  <source srcset="/img/campus.avif" type="image/avif">
  <source srcset="/img/campus.webp" type="image/webp">
  <img id="photo" src="/img/campus.jpg" alt="Students at the campus gate" width="400" height="300">
</picture>

The image files are placeholders served by a local test server, so the check read the markup and not the chosen file. 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

  • JPEG suits photos; PNG suits sharp images; SVG suits logos and icons.
  • WebP and AVIF are often smaller, but check support.
  • picture with source type offers formats in order.
  • The img inside picture is the fallback and holds alt and size.
  • Set width and height to avoid layout shift.

Common mistakes

  • Using PNG for large photos, which makes pages heavy.
  • Using a JPEG for a logo, which gets blurry edges and cannot be transparent.
  • Adding a new format with no fallback img.

Follow-ups

  • Why should width and height be set on the img?
  • When is SVG a bad choice?

Tips

  • Match format to content: photo, drawing, sharp screenshot.
  • Say that picture picks the first source the browser supports, and img is the fallback.
87.html-css-0087Easyfresher

What are data-* attributes, and how do you read them in JavaScript and CSS?

data-* attributes store custom values on elements. JavaScript reads them with el.dataset (dashes become camelCase, values are strings), and CSS can match them with attribute selectors or show them with attr() in content. They are not private and not for real content.

Full answer

A data-* attribute lets you store your own small piece of information on an HTML element. The name starts with data-, followed by a name in lowercase, for example data-course-id="42" or data-status="open". They are valid HTML, so they do not break validators, and they do not appear on the page.

In JavaScript, the dataset property gives access. el.dataset.courseId reads data-course-id. The dashes become camel case. Values are always strings, so convert numbers yourself with Number(). Writing el.dataset.status = "closed" changes the attribute.

In CSS you can use the value in two ways:

  • Attribute selectors: [data-status="open"] { ... } styles elements by value. This is useful for state that JavaScript sets, and it avoids long class names.
  • attr() inside content: a::after { content: attr(data-hint); } shows the text from the attribute in a pseudo-element.

Keep these rules in mind. Do not put secrets or important content in data attributes, because anyone can read them in the page source. Do not use them for text that screen readers must read: text inside content from attr() may not be read the same way in every case, and search engines do not treat it as page content. Use real text for real content.

The script reads 42 as a number and changes the status to closed. The border turns red because the attribute selector matches the new value. The text "(beginner)" is added after the title from the data-level attribute.

In the example the course title is real text in the element, and only the extra label comes from the attribute.

html
<style>
  .course { padding: 8px; border: 1px solid #999; }
  .course[data-status="open"] { border-color: green; }
  .course[data-status="closed"] { border-color: #c00; color: #666; }
  .course::after { content: " (" attr(data-level) ")"; font-size: 0.8em; }
</style>
<div class="course" id="c" data-course-id="42" data-status="open" data-level="beginner">HTML basics</div>
<script>
  const el = document.getElementById("c");
  window.idValue = Number(el.dataset.courseId);
  el.dataset.status = "closed";
</script>

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

  • Names start with data- and use lowercase letters and dashes.
  • dataset converts data-course-id to courseId.
  • Values are always strings.
  • CSS can use [data-x="y"] selectors and attr().
  • Do not store secrets or important text in them.

Common mistakes

  • Expecting dataset values to be numbers or booleans. They are always strings.
  • Storing secrets or large data in data attributes.
  • Putting meaningful text only in attr() content, which is not reliable for assistive technology or search.

Follow-ups

  • How do you remove a data attribute with JavaScript?
  • Why should important text not come only from attr()?

Tips

  • Show the camel case rule: data-course-id becomes dataset.courseId.
  • Say that values are strings, with a one-line example.
88.html-css-0088Easyfresher

How do you style a data table so it is neat and easy to read, including zebra rows and a sticky header?

Use border-collapse: collapse, cell padding, right-aligned numbers, tbody tr:nth-child(even) for stripes and position: sticky with a background on thead th for the header. Wrap wide tables in an overflow container. Do not change table display values.

Full answer

A table already has the right structure in HTML (thead, tbody, th, td). CSS then controls the look.

Main properties:

  • border-collapse: collapse merges the borders of neighbouring cells into one line. The default, separate, draws a double border with gaps. With border-spacing you can control the gap in separate mode.
  • padding on th and td gives the text room.
  • text-align: left for text, right for numbers so digits line up. font-variant-numeric: tabular-nums makes digits the same width.
  • Zebra stripes: tbody tr:nth-child(even) { background: #f5f5f5; }. They help the eye follow a row.
  • A sticky header: thead th { position: sticky; top: 0; background: #fff; }. The header stays visible while the body scrolls. The cells need a background, or the rows show through. Put the table in a box with a fixed height and overflow: auto, or let the page scroll.
  • A caption gives the table a title. Style it like any other block.

For small screens, a wide table should be inside a wrapper with overflow-x: auto, so the page itself does not scroll sideways.

Do not use tables for page layout, and do not change display on table elements without thinking: display: block on a tr removes table semantics in some browsers and for some assistive technology.

The table has single lines between rows, right-aligned prices and grey stripes on every second row. When the box is scrolled, the header row stays at the top.

Check keyboard and screen reader behaviour in a real browser if the table is important.

html
<style>
  .wrap { height: 100px; overflow: auto; width: 260px; }
  table { border-collapse: collapse; width: 100%; font: 14px sans-serif; }
  caption { text-align: left; font-weight: bold; padding: 4px 0; }
  th, td { padding: 6px 8px; border-bottom: 1px solid #ccc; text-align: left; }
  td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
  thead th { position: sticky; top: 0; background: #fff; }
  tbody tr:nth-child(even) { background: #f5f5f5; }
</style>
<div class="wrap" id="wrap">
  <table id="t">
    <caption>Fees</caption>
    <thead><tr><th scope="col">Course</th><th scope="col" class="num">Price</th></tr></thead>
    <tbody id="tb">
      <tr><td>HTML</td><td class="num">10</td></tr>
      <tr><td>CSS</td><td class="num">20</td></tr>
      <tr><td>JavaScript</td><td class="num">30</td></tr>
      <tr><td>React</td><td class="num">40</td></tr>
      <tr><td>Node</td><td class="num">50</td></tr>
      <tr><td>SQL</td><td class="num">60</td></tr>
    </tbody>
  </table>
</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

  • border-collapse: collapse merges neighbouring borders.
  • Padding and alignment make cells readable.
  • nth-child(even) on rows creates zebra stripes.
  • position: sticky on thead th keeps the header visible.
  • A scroll wrapper keeps wide tables from breaking the page.

Common mistakes

  • Leaving the default border-spacing so borders look double and gappy.
  • Making a sticky header without a background, so rows show through while scrolling.
  • Setting display: block or flex on table rows, which can remove table semantics.

Follow-ups

  • Why does a sticky th need a background?
  • How do you handle a wide table on a phone?

Tips

  • Name border-collapse first, because every interviewer expects it.
  • Mention right-aligned numbers and tabular-nums as a small detail that shows care.
89.html-css-0089Easyfresher

How do you style link states, and why does the order of :link, :visited, :hover and :active matter?

Links have :link, :visited, :hover, :focus-visible and :active states. They have equal specificity, so source order decides: use LVHA order. Keep the focus ring and an underline, and remember that :visited can style only a few properties for privacy.

Full answer

A link can be in several states at once, and each state has its own pseudo-class.

  • :link is an unvisited link, and :visited is one that is in the history.
  • :hover is when a pointer is over it.
  • :focus and :focus-visible apply when it has keyboard focus.
  • :active is while it is being pressed.

All of these pseudo-classes have the same specificity. When two rules match and both set the same property, the later one wins. A link can be visited and hovered at the same time. If :hover comes before :visited in the file, the visited colour overrides the hover colour for visited links, and the hover seems broken. The usual safe order is LVHA: :link, :visited, :hover, :active. Many people add :focus-visible next to :hover.

A simpler way is to style a for the base look, then a:hover and a:focus-visible, and not use :link at all. The base rule has lower specificity than the pseudo-class rules, so order matters less.

Privacy limits :visited. Browsers allow only a few properties on it, such as colour and border colour, and they report the unvisited value to scripts. This stops sites from finding out your history.

Never remove the focus outline without a replacement. Links should not rely on colour alone. Underline them in text, or give another clue.

At rest the link is blue and underlined. On hover, it is darker blue and the underline gets thicker. With keyboard focus, a ring appears. While pressed, it is red. Because :hover comes after :visited, a visited link also gets the hover colour.

Test with the mouse, with the Tab key, and for visited links in a real browser.

html
<style>
  a { color: #0a58ca; text-decoration: underline; }
  a:visited { color: #6f42c1; }
  a:hover { color: #003d99; text-decoration-thickness: 3px; }
  a:focus-visible { outline: 3px solid #0a58ca; outline-offset: 2px; }
  a:active { color: #c00; }
</style>
<p>Read the <a id="a" href="#top">course guide</a> now.</p>

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

  • Link state pseudo-classes have the same specificity.
  • Use the order :link, :visited, :hover, :active, with :focus-visible near hover.
  • :visited allows only a few properties for privacy.
  • Do not remove the focus outline.
  • Do not rely on colour alone for links.

Common mistakes

  • Writing :hover before :visited, so hover does not work on visited links.
  • Removing the underline and the focus outline, which leaves keyboard users and colour blind users with no clue.
  • Using :focus for mouse clicks and showing a ring that annoys some users, instead of :focus-visible.

Follow-ups

  • What does :focus-visible do that :focus does not?
  • Why can you only change a few properties on :visited?

Tips

  • Say LVHA and explain why: same specificity, so later rules win.
  • Mention that :visited has privacy limits on what you can style.
90.html-css-0090Mediummid

Which special pseudo-elements let you style selected text, input placeholders, list markers and the first line, and what are their limits?

::selection styles highlighted text, ::placeholder styles input hints, ::marker styles bullets and numbers, and ::first-line and ::first-letter style the start of a block. Each allows only some properties, and contrast and real labels still matter.

Full answer

Some parts of a page have no element of their own, but CSS can still reach them with pseudo-elements.

  • ::selection styles text that the user highlights. Only a few properties work: color, background-color, text-decoration and text-shadow. Keep enough contrast, because many people use selection to read.
  • ::placeholder styles the hint text in an input. Placeholder text is often low contrast by default. Do not use it in place of a label, and make sure that the colour is still readable.
  • ::marker styles the bullet or number of a list item. Allowed properties include color, font-size and content. Layout properties such as margin have limited effect. It is a clean way to colour bullets without adding extra elements.
  • ::first-line styles the first line of a block as it is laid out. If the window gets narrower, the first line changes, and the style moves with it. Only font, colour, background and some text properties work.
  • ::first-letter styles the first letter. It is used for drop caps with float and a larger font-size.

These are pseudo-elements, so they use two colons. Do not group a selector with one of them and another unsupported selector in the same rule, because the browser may drop the whole rule if it does not understand one part. Write separate rules when you need vendor-specific versions.

The user's selection is yellow with black text. The placeholder is dark grey and fully opaque (Firefox lowers opacity on placeholders by default, so the example sets it). The list bullet is blue and bold. Only the first line of the paragraph is bold.

The input still has a real label, because a placeholder disappears when the user types and is not a good name for the field.

html
<style>
  ::selection { background: #ffe066; color: #000; }
  input::placeholder { color: #595959; opacity: 1; }
  li::marker { color: #0a6cff; font-weight: bold; }
  p::first-line { font-weight: bold; }
  p { width: 14em; font: 16px/1.4 sans-serif; }
</style>
<label for="n">Name</label>
<input id="n" placeholder="Your full name">
<ul><li id="li">Item one</li></ul>
<p id="p">This paragraph is long enough to wrap onto a second line in a narrow box.</p>

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

  • ::selection allows color, background, text-decoration and text-shadow.
  • ::placeholder needs enough contrast and is not a label.
  • ::marker styles list bullets and numbers.
  • ::first-line follows the actual wrapped first line.
  • Pseudo-elements use two colons.

Common mistakes

  • Using ::placeholder as the only label for an input.
  • Setting a light placeholder colour that fails contrast.
  • Expecting layout properties like margin or width to work on ::selection or ::first-line.

Follow-ups

  • Which properties can you set on ::selection?
  • Why is a placeholder not a replacement for a label?

Tips

  • Say that these pseudo-elements allow only a limited set of properties.
  • Mention contrast for both selection and placeholder.
91.html-css-0091Mediummid

How do you build a page layout with grid-template-areas and change it for small screens?

grid-template-areas draws the layout as strings of area names and items use grid-area to take a place. For a responsive version, define a one-column template as default and redefine the template in a min-width media query. Keep the HTML order logical.

Full answer

grid-template-areas lets you draw the layout as text. Each string is a row. Each word is a name for a cell, and a name repeated across cells makes one area. A dot . means an empty cell. Areas must be rectangles.

Then each item picks its place with grid-area: name. The HTML order is unchanged, only the visual place is set in CSS.

For a typical page:

  • Wide screens: header on top across both columns, sidebar on the left, main on the right, footer at the bottom.
  • Small screens: one column, with the areas stacked in the order that makes sense to read.

To switch, write the one-column layout as the default and add a media query for the wide layout. This is mobile first. Only the template changes. The items keep their grid-area names.

Some points:

  • grid-template-columns sizes the columns. 200px 1fr is a fixed sidebar and a flexible main.
  • If an item has a name that is not in the template, the browser creates implicit tracks. Check spelling.
  • Visual reordering does not change the order in which screen readers and keyboard users move through the page. Keep HTML in a logical order, and do not use areas to put important content out of sequence.

Below 600px, the four blocks are stacked: header, main, sidebar, footer. At 600px and above, the header and footer span two columns, and the sidebar sits to the left of main, although it comes after main in the HTML.

Resize the window to check both layouts, and tab through the page to see the order is still sensible.

html
<style>
  body { margin: 0; font-family: sans-serif; }
  .page {
    display: grid; gap: 8px;
    grid-template-columns: 1fr;
    grid-template-areas: "header" "main" "side" "footer";
  }
  @media (min-width: 600px) {
    .page {
      grid-template-columns: 160px 1fr;
      grid-template-areas:
        "header header"
        "side   main"
        "footer footer";
    }
  }
  header { grid-area: header; background: #cde; }
  aside { grid-area: side; background: #fdc; }
  main { grid-area: main; background: #dfc; }
  footer { grid-area: footer; background: #eee; }
</style>
<div class="page">
  <header id="h">Header</header>
  <main id="m">Main</main>
  <aside id="s">Sidebar</aside>
  <footer id="f">Footer</footer>
</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

  • Each string is a row; repeated names form an area.
  • Areas must be rectangles; a dot is an empty cell.
  • grid-area on items assigns them to a named area.
  • Redefine the template in a media query to change the layout.
  • Visual reordering does not change reading or tab order.

Common mistakes

  • Writing an area map that is not a rectangle, which makes the whole declaration invalid.
  • Using grid areas to move important content far from its place in the HTML, which confuses keyboard and screen reader users.
  • Starting with the wide layout and removing parts for mobile, instead of starting with the small layout.

Follow-ups

  • What happens if an item names an area that does not exist?
  • How does a dot in grid-template-areas work?

Tips

  • Explain that the strings are rows and the repeated names are areas.
  • Mention reading order as the downside of visual reordering.
92.html-css-0092Mediummid

What does the flex order property do, and what problem does it create for keyboard and screen reader users?

order sorts flex and grid items visually, with lower values first and ties in HTML order. It does not change the DOM order, so keyboard focus and screen readers go in a different sequence than the screen, which is confusing. Keep the DOM order meaningful and use order only for small changes.

Full answer

order is a property for flex and grid items. Items are drawn sorted by their order value, lowest first, and the default is 0. Items with the same value keep their HTML order. Negative values are allowed, so order: -1 moves an item to the front.

It is easy to use. For example, a card can have the image after the text in the HTML, and order: -1 on the image shows it first on screen.

The problem is that order changes only the visual order. The DOM order stays the same. Keyboard focus, screen readers and the text cursor all follow the DOM order. If the screen shows A, B, C but the DOM is C, A, B, then Tab moves C, A, B. The focus appears to jump around, which is confusing, and it can fail accessibility rules that require a meaningful sequence.

Good practice:

  • Put content in the DOM in the order that makes sense when read. Use order only for small changes where focus order does not matter, such as a decorative item.
  • If the visual order must change for a screen size, check the tab order after the change.
  • For very large changes, change the HTML.
  • flex-direction: row-reverse and column-reverse have the same issue.

On screen the third link in the HTML is drawn first. When the Tab key is pressed, focus goes to the first link in the DOM, which is drawn in the second place, then to the next one, and the last focus lands on the link drawn at the left. The focus appears to jump from the second box to the third and then back to the first.

A simple check is to press Tab through your page and watch whether the focus ring moves in a path that makes sense.

html
<style>
  .row { display: flex; gap: 8px; }
  .row a { padding: 4px 8px; border: 1px solid #999; }
  .row a.first { order: -1; }
</style>
<div class="row" id="row">
  <a href="#a" id="a">Second on screen</a>
  <a href="#b" id="b">Third on screen</a>
  <a href="#c" id="c" class="first">First on screen</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

  • order sorts items by value; default is 0.
  • Ties keep the HTML order.
  • Only the visual order changes; DOM order stays.
  • Focus and screen readers follow the DOM order.
  • row-reverse and column-reverse have the same problem.

Common mistakes

  • Using order or row-reverse to restructure the page and ignoring that tab order stays in the DOM order.
  • Assuming screen readers read the visual order.
  • Using large order values on many items, which makes the layout hard to follow in the code.

Follow-ups

  • What is the default order value, and how are ties handled?
  • How do row-reverse and column-reverse relate to this issue?

Tips

  • Say that order is visual only and the DOM order drives focus and reading.
  • Give a safe use and an unsafe use.
93.html-css-0093Mediummid

How do you keep a footer at the bottom of the window on short pages without fixed positioning?

Make body at least window height with min-height: 100vh (and 100dvh after it), and use a column flex layout with main { flex: 1 } or a grid with rows auto 1fr auto. The footer stays at the bottom on short pages and moves down on long ones. Remove the default body margin.

Full answer

On a short page the content does not fill the window, so the footer sits in the middle of the screen with empty space under it. The footer should be at the bottom of the window on short pages and after the content on long pages. position: fixed on the footer is wrong, because then it would cover content on long pages.

The modern fix makes the body a column that is at least as tall as the window and lets the main part take the free space.

With flexbox:

css
body { min-height: 100vh; display: flex; flex-direction: column; }
main { flex: 1; }

With grid:

css
body { min-height: 100vh; display: grid; grid-template-rows: auto 1fr auto; }

The header and footer take their own height, and 1fr gives all the rest to main.

Use min-height and not height, so the page can still grow when there is a lot of content. On phones, 100vh can be taller than the visible area when the address bar is shown. The newer dvh unit follows the visible height. Provide 100vh first as a fallback and 100dvh after it, because a browser that does not know dvh ignores that line. Also remove the default 8px body margin, or the page will be a little too tall and scroll.

With only a line of content, the footer's bottom edge is at the bottom edge of the window, and main fills the gap. If more content is added to main, the footer is pushed down and the page scrolls, with nothing overlapping.

Check the layout on a short page, on a very long page, and on a phone.

html
<style>
  html, body { margin: 0; }
  body {
    min-height: 100vh;
    min-height: 100dvh;
    display: grid;
    grid-template-rows: auto 1fr auto;
    font-family: sans-serif;
  }
  header { background: #cde; padding: 8px; }
  main { padding: 8px; }
  footer { background: #333; color: #fff; padding: 8px; }
</style>
<header id="h">Header</header>
<main id="m">Short content</main>
<footer id="f">Footer</footer>

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

  • Body needs min-height equal to the window height.
  • Flex column with main flex: 1 or grid rows auto 1fr auto both work.
  • Use min-height, so long content can still grow the page.
  • Write 100vh first and 100dvh after it.
  • Reset the default body margin.

Common mistakes

  • Using position: fixed or absolute for the footer, which overlaps content on long pages.
  • Using height: 100vh on the body, which makes the layout break when content is taller.
  • Forgetting the default body margin, which creates a small unwanted scroll.

Follow-ups

  • Why is min-height used instead of height?
  • What does the 1fr row do in the grid version?

Tips

  • Say min-height, not height, and give the reason.
  • Mention the 100vh then 100dvh fallback pair.
94.html-css-0094Mediummid

How do you build an accessible on/off switch with HTML, CSS and a little JavaScript?

Use a button with role="switch" and aria-checked that a script toggles, or a styled checkbox in a form. Style the state from the attribute or :checked, keep a visible focus ring and do not show state by colour alone.

Full answer

Start with the right element. Two good options:

  1. A button with role="switch" and aria-checked="true" or "false". A script flips the value on click. A button is focusable and works with Enter and Space, with no extra code.
  2. A real checkbox, styled to look like a switch. This is the simplest way when the control is part of a form, because the browser keeps the state, and :checked styles it. Keep the label connected with for or by wrapping.

A common mistake is a div or span styled as a switch. It cannot be reached by the keyboard, and screen readers do not know it is a control.

For the button version:

  • The visible text or aria-label is the name, for example "Email alerts". The name should not change when the state changes, because the state is announced separately. Hide any extra "On" or "Off" text from screen readers with aria-hidden="true".
  • CSS reads the state with an attribute selector: [role="switch"][aria-checked="true"]. This keeps the visual state and the announced state in one place.
  • Add :focus-visible styles, and make the target at least about 24 to 44 CSS pixels so it is easy to hit.
  • Do not show state with colour only. The text "On" or "Off", or the position of the knob, helps users who cannot tell the colours apart.

Clicking the button or pressing Space or Enter while it is focused turns it on. The knob moves, the colours change and the small text changes to "On". The name stays "Email alerts", and the small text is hidden from screen readers, because the switch role already announces the on or off state.

Test with the keyboard and with a screen reader before using this widely.

html
<style>
  .sw { display: inline-flex; align-items: center; gap: 8px; padding: 4px 8px; border: 1px solid #666; border-radius: 16px; background: #fff; font: 16px sans-serif; cursor: pointer; }
  .sw .knob { width: 16px; height: 16px; border-radius: 50%; background: #666; transition: transform 0.15s; }
  .sw[aria-checked="true"] { background: #e6f4ea; border-color: #137333; }
  .sw[aria-checked="true"] .knob { background: #137333; transform: translateX(8px); }
  .sw:focus-visible { outline: 3px solid #0a6cff; outline-offset: 2px; }
</style>
<button type="button" class="sw" id="sw" role="switch" aria-checked="false">
  <span class="knob"></span><span>Email alerts</span><span id="state" aria-hidden="true">Off</span>
</button>
<script>
  const sw = document.getElementById("sw");
  sw.addEventListener("click", () => {
    const on = sw.getAttribute("aria-checked") === "true";
    sw.setAttribute("aria-checked", String(!on));
    document.getElementById("state").textContent = on ? "Off" : "On";
  });
</script>

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 a button with role=switch, or a styled checkbox.
  • aria-checked holds the state for assistive technology.
  • CSS can style [aria-checked="true"] so the visual state matches.
  • Keep :focus-visible styles and a large target.
  • Do not use colour as the only state clue.

Common mistakes

  • Building the switch from a div with no keyboard access or role.
  • Changing the accessible name when the state changes, so a screen reader announces the state twice.
  • Showing the state with colour alone.

Follow-ups

  • Why is a real button better than a div here?
  • When would you use a styled checkbox instead?

Tips

  • Name both options: button with role=switch, and a styled checkbox. Say when each fits.
  • Say that CSS should read the ARIA attribute, so the visual and the announced state cannot drift apart.
95.html-css-0095Mediummid

How do you build a skeleton loading state with CSS and keep it accessible?

A skeleton uses grey blocks sized like the real content, with an optional shimmer animation turned off for reduced motion. Mark the region with aria-busy, hide the shapes from assistive technology and announce loading and loaded states with a status message.

Full answer

A skeleton screen shows grey shapes in the layout of the content while data loads. It makes the wait feel shorter and reserves the right space, so the page does not jump when the real content arrives.

How to build it:

  1. Make shapes with simple elements and a grey background: a bar for a title, shorter bars for text lines, and a square for an image. Give them the same height and width as the real content, so the layout does not shift.
  2. Add a soft shimmer. A linear-gradient background that is larger than the element and moves with @keyframes on background-position is a common approach.
  3. Respect users who ask for less motion. Turn the animation off in @media (prefers-reduced-motion: reduce), and keep the plain grey blocks.

Accessibility needs attention. Grey shapes mean nothing to a screen reader user, so:

  • Set aria-busy="true" on the region that is loading. When the content is ready, replace the skeleton, and set aria-busy="false" or remove it.
  • Hide the placeholder shapes from assistive technology with aria-hidden="true", or make them empty elements with no text.
  • If it matters, announce the loading and the result with a polite live region, such as a visually hidden "Loading courses" message.

Do not leave a skeleton forever. If loading fails, replace it with an error message and a retry button.

The card shows a title bar and two text bars with a moving shine. With reduced motion, they are still and grey. A screen reader reads the status message and knows the region is busy.

When the data arrives, replace the placeholder with the real content, update the status text, and set aria-busy to false.

html
<style>
  .sk { background: linear-gradient(90deg, #e5e5e5 25%, #f2f2f2 50%, #e5e5e5 75%); background-size: 200% 100%; animation: shimmer 1.2s linear infinite; border-radius: 4px; }
  .sk.title { height: 20px; width: 60%; margin-bottom: 8px; }
  .sk.line { height: 12px; width: 100%; margin-bottom: 6px; }
  @keyframes shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } }
  @media (prefers-reduced-motion: reduce) { .sk { animation: none; } }
</style>
<section id="card" aria-busy="true" aria-labelledby="h">
  <h2 id="h" style="position:absolute;left:-9999px">Course card</h2>
  <div aria-hidden="true">
    <div class="sk title"></div>
    <div class="sk line"></div>
    <div class="sk line" style="width:80%"></div>
  </div>
  <p id="status" role="status" style="position:absolute;left:-9999px">Loading course</p>
</section>

Checked by reading the computed animation, with and without the reduced motion preference emulated in Chrome. No screen reader 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

  • Skeleton blocks reserve space and reduce layout shift.
  • A moving gradient background gives a shimmer.
  • Disable the animation in prefers-reduced-motion: reduce.
  • aria-busy and aria-hidden keep the placeholder quiet for screen readers.
  • Replace it with an error and retry if loading fails.

Common mistakes

  • Using an infinite shimmer with no reduced motion option.
  • Skeleton shapes with different sizes from the real content, so the page still jumps when loaded.
  • Leaving the skeleton forever when a request fails.

Follow-ups

  • How would you handle a failed request?
  • Why use a gradient and background-position instead of animating width?

Tips

  • Link skeletons to layout shift: same size as the real content.
  • Mention aria-busy, aria-hidden and a status message.
96.html-css-0096Mediummid

How would you build a responsive navigation that collapses into a menu button on small screens?

Use a nav with a link list. On small screens hide the list with display: none and show a button with aria-expanded that a script toggles, and close it on Escape. Do not use role=menu for site navigation.

Full answer

Start with the markup that works with no CSS: a nav that holds a list of links. A screen reader user can find it as a navigation landmark, and the links work with the keyboard.

On wide screens, show the links in a row. On narrow screens, hide the list and show a button that opens it. Rules for the button:

  • Use a real button with type="button", not a div. It has an accessible name, such as "Menu".
  • aria-expanded="false" or "true" tells assistive technology whether the list is open.
  • aria-controls can point to the list id. Its support is uneven, so do not rely on it alone.
  • A small script toggles aria-expanded and shows or hides the list. The CSS reads the attribute, so the visual and announced state stay in sync.
  • Escape should close the menu and return focus to the button.

Do not use role="menu" for a normal site navigation. That role is for application-style menus with arrow-key behaviour, and it changes how screen readers handle the content. A list of links inside a nav is the right pattern.

Hide the closed list with display: none on small screens, so its links are not focusable. Do not hide it with only opacity: 0 or by moving it off screen, because then keyboard users can still tab to invisible links.

Use min-width queries (mobile first), and show the button only below the breakpoint.

On a phone width the page shows only the Menu button. Clicking it shows the three links under it, and clicking again hides them. Escape closes the menu and puts focus back on the button. On wide screens the button is gone and the links are in a row.

Test with the keyboard only, and at several widths between the two layouts.

html
<style>
  body { margin: 0; font-family: sans-serif; }
  nav ul { list-style: none; margin: 0; padding: 0; display: none; }
  nav ul a { display: block; padding: 8px 12px; }
  #btn { padding: 8px 12px; }
  #btn[aria-expanded="true"] + ul { display: block; }
  @media (min-width: 600px) {
    #btn { display: none; }
    nav ul { display: flex; }
  }
</style>
<nav aria-label="Main">
  <button type="button" id="btn" aria-expanded="false" aria-controls="menu">Menu</button>
  <ul id="menu">
    <li><a href="/courses" id="first">Courses</a></li>
    <li><a href="/pricing">Pricing</a></li>
    <li><a href="/help">Help</a></li>
  </ul>
</nav>
<script>
  const btn = document.getElementById("btn");
  btn.addEventListener("click", () => {
    btn.setAttribute("aria-expanded", String(btn.getAttribute("aria-expanded") !== "true"));
  });
  document.addEventListener("keydown", (e) => {
    if (e.key === "Escape" && btn.getAttribute("aria-expanded") === "true") {
      btn.setAttribute("aria-expanded", "false");
      btn.focus();
    }
  });
</script>

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

  • Start with a nav and a list of links.
  • A real button with aria-expanded controls the list.
  • CSS can show the list with [aria-expanded="true"] + ul.
  • Hide closed items with display: none so focus cannot reach them.
  • Escape should close and return focus to the button.

Common mistakes

  • Hiding the closed menu with opacity or off-screen positioning, so keyboard focus enters invisible links.
  • Using role="menu" for ordinary site navigation.
  • Not updating aria-expanded, so screen readers do not know the state.

Follow-ups

  • Why use display: none for the closed list?
  • What should happen to focus when the menu closes with Escape?

Tips

  • Say that the markup is a normal nav with a list of links first, and the button is an enhancement.
  • Mention why role=menu is the wrong role for site navigation.
97.html-css-0097Hardsenior

What does the @scope rule do, and how does it compare with BEM and nesting?

@scope applies rules only inside a scope root, optionally stopping at a lower boundary. It adds proximity to the cascade and does not add the root's specificity. It is newer than BEM or nesting, so check support and keep a fallback outside the block.

Full answer

@scope limits a group of rules to a part of the page. You give it a scope root, and the rules inside only match elements that are inside that root.

css
@scope (.card) {
  h2 { font-size: 1.2rem; }
  a { color: teal; }
}

Here h2 and a styles apply only inside .card. There is no need for a long class name like card__title just to avoid clashes.

Two features set it apart from nesting.

  • A scope limit, written with to: @scope (.card) to (.card-footer). Styles apply inside the card but stop at the footer. This is called a donut scope. It stops styles from leaking into nested components.
  • Proximity in the cascade. If two scopes both match an element, the rule from the scope root that is closest to the element wins, before source order is considered. This helps when a component is nested inside another component, and both set the same properties. The proximity rule comes after specificity.

Two points on specificity. Selectors inside @scope do not get extra specificity from the scope root, unlike the same selector written as .card h2. The :scope pseudo-class refers to the root itself.

Compare with the other ways:

  • BEM solves clashes with names. It works everywhere, but names are long.
  • Nesting is only a way to write selectors. .card { h2 { } } is equal to .card h2 and adds specificity of the parent.
  • CSS Modules rename classes at build time.

@scope is a newer feature. Check the support table before relying on it, and keep a fallback, for example plain class selectors, for browsers that ignore the rule. An unsupported @scope block is skipped completely, so a fallback must live outside it.

The title inside the card is red. The title outside the card is black. The title inside the footer is also black, because the scope ends at .card-footer.

Where the browser does not support @scope, all three titles are black. If red is required, add a fallback rule such as .card > h2 { color: crimson; } before the block.

html
<style>
  h2 { color: black; }
  @scope (.card) to (.card-footer) {
    h2 { color: crimson; }
  }
</style>
<h2 id="out">Outside</h2>
<div class="card">
  <h2 id="in">Inside the card</h2>
  <div class="card-footer"><h2 id="foot">Inside the footer</h2></div>
</div>

Checked in Chrome 156 only. A browser without @scope skips the block, and that case was not 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

  • @scope (root) limits rules to a part of the DOM.
  • A to (limit) clause makes a donut scope.
  • Proximity prefers the closest scope root when specificity ties.
  • Selectors inside do not gain the root's specificity.
  • Unsupported browsers skip the block, so add a fallback.

Common mistakes

  • Using @scope with no fallback and no support check.
  • Expecting it to add the parent's specificity like a nested selector.
  • Forgetting the lower boundary, so styles leak into nested components.

Follow-ups

  • What is a donut scope?
  • Where does proximity come in the order of the cascade?

Tips

  • Explain the two big ideas: a scope root and an optional lower boundary.
  • Say how it differs from nesting: no added specificity, and proximity.
98.html-css-0098Hardsenior

What does @property add to CSS custom properties, and how can it be used to animate a gradient?

@property registers a custom property with a syntax type, an inherits flag and an initial value. The browser then validates values and can interpolate them, so a registered angle can animate a gradient. It is newer, so check support and keep a static fallback.

Full answer

A normal custom property, such as --angle, is just text to the browser. It does not know that 45deg is an angle. This has two results. The value is not checked, and it cannot be animated smoothly: a transition from 0deg to 90deg on a plain custom property jumps at the halfway point, because there is nothing to calculate between two strings.

@property registers a custom property with a type. You give it three descriptors:

  • syntax: the type, for example "<angle>", "<color>", "<length>" or "<number>".
  • inherits: true or false. Setting false can help performance when the value does not need to pass down.
  • initial-value: the default, and it is required for most types.

After that, the browser parses the value, rejects invalid ones (falls back to the initial value), and can interpolate between two values. The classic use is animating a gradient angle or a colour stop. A gradient itself cannot be animated, but a registered angle that the gradient reads can.

The same registration is available in JavaScript with CSS.registerProperty().

It is a newer feature, so check the support table. Without support, the page should still look fine. With the example below, the gradient is simply static if the property is not registered.

When the pointer enters the box, the gradient turns smoothly from 0 to 90 degrees over half a second. In the second box, --bad: red is not a length, so it is thrown away and the padding uses the initial value of 4px.

Without the registration, the hover would flip the gradient angle at once and not animate.

html
<style>
  @property --angle {
    syntax: "<angle>";
    inherits: false;
    initial-value: 0deg;
  }
  .box {
    width: 160px; height: 80px;
    background: linear-gradient(var(--angle), #0a6cff, #ff6a00);
    transition: --angle 0.5s;
  }
  .box:hover { --angle: 90deg; }
  @property --bad { syntax: "<length>"; inherits: false; initial-value: 4px; }
  .check { --bad: red; padding: var(--bad); }
</style>
<div class="box" id="box"></div>
<div class="check" id="check">Invalid value falls back</div>

Checked in Chrome 156 only. The check read the value part way through the transition to confirm that it is interpolated. 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

  • Plain custom properties are untyped text.
  • @property sets syntax, inherits and initial-value.
  • Registered properties are validated and interpolated.
  • Animating a registered angle animates a gradient.
  • Check the support table and keep a fallback.

Common mistakes

  • Expecting plain custom properties to transition smoothly.
  • Registering a property with no initial-value for a type that requires one, which makes the rule invalid.
  • Relying on @property for essential behaviour without a fallback.

Follow-ups

  • Why can a plain custom property not be animated smoothly?
  • What does inherits: false do?

Tips

  • Say what registration adds: type checking, a default and interpolation.
  • Give the gradient angle example, because it is the most common real use.
99.html-css-0099Hardsenior

How do you make a whole card clickable without wrapping everything in a link and harming accessibility?

Use one real link, usually on the title, and expand its ::after to cover the card with position absolute and inset 0 inside a position: relative card. Raise other links with z-index, and draw the focus outline around the card. The link name stays short.

Full answer

A common request is that the whole card should be clickable. There are two simple but poor ways:

  • Wrap the entire card in one a. The link name becomes everything inside the card, so a screen reader reads a very long link. Nested buttons or links inside are invalid HTML.
  • Put a click handler on the whole card with JavaScript. Keyboard and screen reader users get nothing, and "open in new tab" does not work.

A better pattern is the stretched link. The card has one real link, usually on the title. A pseudo-element on that link expands to cover the whole card, so a click anywhere on the card follows the link.

Steps:

  1. The card gets position: relative.
  2. The link's ::after is content: ""; position: absolute; inset: 0;.
  3. Other interactive elements in the card, such as a secondary link or button, get position: relative; z-index: 1 so they sit above the stretched area and still work.
  4. Add a focus style on the card with :focus-within, or on the link. The focus ring of the link only wraps the title, so show it on the whole card with .card:has(a:focus-visible) or by styling the pseudo-element's outline.
  5. Text selection inside the card is blocked in the stretched area, which is a known trade-off.

The link name is only the title, such as "HTML for beginners", which is short and clear.

Clicking the empty area of the card follows the main link. Clicking the small tag link still goes to its own address, because it is raised above the stretched area. When the title link has keyboard focus, the outline is drawn around the whole card.

Test with a screen reader, because the link list should show short, clear names like the title.

html
<style>
  .card { position: relative; width: 220px; padding: 12px; border: 1px solid #999; font-family: sans-serif; }
  .card h3 { margin: 0 0 8px; }
  .card h3 a { color: inherit; text-decoration: none; }
  .card h3 a::after { content: ""; position: absolute; inset: 0; }
  .card a.tag { position: relative; z-index: 1; }
  .card:hover { background: #f5f8ff; }
  .card h3 a:focus-visible::after { outline: 3px solid #0a6cff; outline-offset: 2px; }
</style>
<div class="card" id="card">
  <h3><a href="#course" id="main">HTML for beginners</a></h3>
  <p>Learn tags, links and forms.</p>
  <a class="tag" href="#tag-html" id="tag">HTML</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

  • Wrapping the whole card in a link gives a long, noisy link name.
  • A stretched link uses a ::after pseudo-element with inset: 0.
  • The card needs position: relative.
  • Inner links need position: relative and a z-index.
  • Show focus on the whole card.

Common mistakes

  • Wrapping the whole card in one link, so the link name is a long paragraph.
  • Forgetting z-index on inner links and buttons, so the stretched area blocks them.
  • Showing the focus ring only around the small title link.

Follow-ups

  • How do you keep a secondary link inside the card clickable?
  • What is the downside of a stretched link for text selection?

Tips

  • State the problem with a wrapped card: long link name and invalid nesting.
  • Describe the stretched link in two steps: relative card and absolute pseudo-element.
100.html-css-0100Hardsenior

What is forced colors mode, and how do you make a custom UI work in it?

Forced colors mode replaces author colours with a few system colours and removes shadows and background images. Keep states visible with borders and outlines, use currentColor in SVG, adjust with system colour keywords in @media (forced-colors: active), and avoid forced-color-adjust: none except for small, careful cases.

Full answer

Forced colors mode is an operating system feature, such as Windows contrast themes. When it is on, the browser replaces many of your colours with a small set chosen by the user, so that text is easy to read. The CSS media feature is forced-colors: active.

The browser changes properties such as color, background-color, border-color and outline-color, and removes box-shadow and background images in many cases. Text shadows are removed too. SVG fills and strokes are not changed unless they use currentColor or a system colour.

This causes bugs in custom UI:

  • A custom checkbox or switch drawn only with background colour can become invisible, because the background is replaced.
  • Information shown only by a background colour or shadow disappears. A focus ring made with box-shadow is not shown, but a real outline is kept.
  • Icons in SVG with a fixed fill can vanish on a forced dark background.

Fixes:

  1. Use real borders and outlines for states, not only background or shadow.
  2. Use currentColor in SVG so icons follow the text colour.
  3. Use system colour keywords such as ButtonText, Canvas, CanvasText, Highlight and LinkText inside @media (forced-colors: active) where a manual rule is needed.
  4. If you must keep your own colour for a part, set forced-color-adjust: none on that element, with care, and use system colours inside it. Do not set it on the whole page.
  5. Use transparent borders, such as border: 2px solid transparent, so there is something for forced mode to colour.

Test by turning on a contrast theme in the operating system, or with DevTools emulation of forced-colors.

In normal mode the chip is blue with white text and a blue shadow ring on focus. In forced colors mode, the shadow is removed, but the transparent outline becomes visible in a system colour, and the chip uses the system highlight colours, so it is still clear.

Note that outline: 3px solid transparent is a known technique, because transparent outlines become visible only in forced colors mode.

html
<style>
  .chip { display: inline-block; padding: 4px 12px; border-radius: 12px; background: #e6f0ff; border: 2px solid transparent; }
  .chip[aria-pressed="true"] { background: #0a6cff; color: #fff; }
  button.chip:focus-visible { box-shadow: 0 0 0 3px #0a6cff; outline: 3px solid transparent; }
  @media (forced-colors: active) {
    .chip[aria-pressed="true"] { border-color: Highlight; background: Highlight; color: HighlightText; }
  }
</style>
<button type="button" class="chip" id="chip" aria-pressed="true">Selected</button>

Checked with forced colors emulated in Chrome, not with a real operating system contrast theme. 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

  • Forced colors mode is controlled by the user's operating system.
  • It changes colours and removes box-shadow in many cases.
  • Use borders and outlines for states and focus.
  • Use currentColor in SVG and system colours in a forced-colors media query.
  • Test with a contrast theme or DevTools emulation.

Common mistakes

  • Using box-shadow as the only focus indicator, which disappears in forced colors mode.
  • Setting forced-color-adjust: none on the whole page.
  • Drawing icons with a fixed fill, so they disappear on the forced background.

Follow-ups

  • Which CSS media feature detects forced colors mode?
  • When is forced-color-adjust: none acceptable?

Tips

  • Explain what the OS does: it replaces colours and removes shadows.
  • Name the transparent outline technique and currentColor for SVG.