← Interview prep

HTML & CSS interview questions

Semantic HTML, CSS layout, and CSS interview depth.

193 questions · Page 3 of 10

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

Page 3 of 10

Questions 41–60 of 193 · 0 of 20 on this page marked learned

41.html-css-0041Hardsenior

What are CSS cascade layers (@layer), and how do they change specificity conflicts?

A cascade layer is a named group of rules with a rank. When normal declarations compete, a later layer wins over an earlier one regardless of specificity, and unlayered rules beat all layers. Specificity only decides inside one layer. With !important the layer order is reversed.

Full answer

A cascade layer is a named group of rules with a fixed rank. When two normal declarations compete, the browser checks the layer order before specificity. A rule in a later layer beats a rule in an earlier layer, even if the earlier rule has a much more specific selector. Specificity only decides between rules in the same layer.

Declare the order once at the top: @layer base, components, utilities;. Then put rules inside @layer name { ... } blocks, in any file. Rules that are not in any layer are treated as a final layer that beats all named layers for normal declarations. With !important, the order is reversed: an important rule in an earlier layer beats important rules in later layers.

This solves a common large-codebase problem: a third-party stylesheet or an old reset with #id selectors that you cannot override without !important. Put it in an early layer, and your own simple class selectors win.

The first link is blue. Although #page a is far more specific, components comes after base. The second link is green because utilities is the last layer. The third link is orange, since unlayered rules win over all layers for normal declarations.

You can also import a file into a layer with @import url("vendor.css") layer(vendor);, and nest layers as @layer components.buttons { ... }. Layers do not remove the need for good naming. They let you decide, by design, which group may override which.

Check the support table for the browsers you must serve. A stylesheet that depends on layers has no graceful fallback, because browsers that do not know @layer ignore the whole block.

html
<style>
  @layer base, components, utilities;

  @layer base {
    #page a { color: red; }              /* high specificity, early layer */
  }
  @layer components {
    a { color: blue; }                   /* low specificity, later layer: wins */
  }
  @layer utilities {
    .text-green { color: green; }
  }
  a.unlayered { color: orange; }         /* not in a layer: beats every layer */
</style>
<div id="page">
  <a href="#" id="a1">Plain link</a>
  <a href="#" id="a2" class="text-green">Utility link</a>
  <a href="#" id="a3" class="unlayered text-green">Unlayered link</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

  • Declare the order once: @layer base, components, utilities.
  • Layer order is checked before specificity.
  • Unlayered rules win over layered ones for normal declarations.
  • !important reverses the layer order.
  • Layers let you control overrides without higher specificity or !important.

Common mistakes

  • expecting unlayered styles to be weaker. They are the strongest group for normal declarations, so one stray unlayered rule can override a whole layer.
  • using !important inside layers to win, then finding that important declarations reverse the layer order.

Follow-ups

  • how do layers compare with higher specificity?
  • How do you put an imported stylesheet into a layer?
  • What happens to a layered rule that has the same selector as an unlayered one?

Tips

  • Declare the layer order in one place at the top of your entry stylesheet. A wrong order is hard to spot when layers are declared in several files.
  • Describe the problem layers solve: a third-party file with strong selectors you cannot edit.
  • Say that you declare the order in one place at the top.
42.html-css-0042Hardsenior

What does the :has() selector do, and what are its uses and costs?

A:has(B) matches A when the relative selector B matches something inside or after it. It lets CSS style a card that contains an image, a label whose checkbox is checked or a form that has invalid fields. It takes the specificity of its most specific argument and needs scoping, because it can be costly on large DOMs.

Full answer

:has() is a relational pseudo-class. A:has(B) matches an element A if the selector B, evaluated relative to A, matches something. In practice it lets CSS style an element based on its descendants, or on its following siblings, which was impossible before without JavaScript. People call it the "parent selector", but it is more general.

Relative selectors inside it start with a combinator: :has(> img) means a direct child image, :has(+ p) means the next sibling is a paragraph.

Typical uses:

  • Style a card differently when it contains an image: .card:has(img).
  • Style a label or row when its checkbox is checked: label:has(input:checked).
  • Show an error summary when a form has invalid fields: form:has(:user-invalid) or form:has(:invalid).
  • Change a heading's spacing when a paragraph follows: h2:has(+ p).
  • Quantity-like conditions: ul:has(li:nth-child(4)) matches a list with at least four items.

Its specificity is that of its most specific argument. You cannot nest :has() inside another :has().

The first card becomes a two-column grid because it contains an img. The second stays as a block. Ticking the checkbox gives the label a green background. The list with four items is highlighted yellow, and the one with three is not. The @supports not selector(:has(a)) block is a fallback for browsers that do not know the selector.

Browsers have to re-check :has() rules when the DOM changes anywhere inside the scope, so it is more costly than a simple class selector. Engines optimise common cases, but a broad rule such as body:has(.modal) on a large page is something to measure.

html
<style>
  .card { padding: 8px; border: 1px solid #999; margin-bottom: 8px; }
  .card:has(img) { display: grid; grid-template-columns: 60px 1fr; gap: 8px; }
  .option { display: block; padding: 6px; border: 1px solid #ccc; }
  .option:has(input:checked) { background: #dff5e1; border-color: seagreen; }
  ul:has(li:nth-child(4)) { background: #fff3cd; }
  @supports not selector(:has(a)) { .option { border-style: dashed; } }
</style>
<div class="card" id="c1"><img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" width="60" height="60" alt=""><p>With picture</p></div>
<div class="card" id="c2"><p>Text only</p></div>
<label class="option" id="o1"><input type="checkbox" id="chk"> Notify me</label>
<ul id="short"><li>1</li><li>2</li><li>3</li></ul>
<ul id="long"><li>1</li><li>2</li><li>3</li><li>4</li></ul>

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

  • A:has(B) matches A based on its descendants or later siblings.
  • Relative selectors start with a combinator, as in :has(> img) or :has(+ p).
  • Specificity equals that of the most specific argument.
  • You cannot nest :has() inside :has().
  • Scope it narrowly and use @supports selector(:has(a)) for fallbacks.

Common mistakes

  • assuming :has() is only for parents. It also works for siblings, as in h2:has(+ p), with a leading combinator.
  • shipping a design that breaks completely without :has(). Use @supports selector(:has(a)) to write a sensible fallback.

Follow-ups

  • how would you style a form that has any invalid field?
  • How do you check support for :has() in CSS?
  • Which uses of :has() can replace small JavaScript scripts?

Tips

  • Scope :has() narrowly. Prefer .card:has(> img) to :has(img) on a high-level container when you can.
  • Give two real uses: a card with an image and a form with invalid fields.
  • Mention performance and fallbacks without being asked.
43.html-css-0043Hardsenior

How does native CSS nesting work, and how does it differ from Sass nesting?

Native CSS nesting lets rules sit inside other rules, with & standing for the parent selector. Nested media and container rules apply to the parent. The parent behaves like :is(), so the nested rule takes the specificity of the parent. Unlike Sass, & cannot be glued to text such as &-title.

Full answer

Native CSS nesting lets you write a rule inside another rule. The inner selector is combined with the outer one, so related styles stay in one block.

The nesting selector & stands for the parent selector. You use it when the inner selector must attach to the parent directly, as in &:hover or &.active. You can place it elsewhere in the selector to wrap the parent, as in .dark &. Conditional group rules such as @media and @container can also be nested, and then they apply to the parent selector without repeating it.

Specificity: the parent in a nested rule behaves like :is() around the parent selector list, so it takes the specificity of the most specific selector in that list. A rule such as #panel { .title { ... } } has the specificity of #panel .title, which is (1,1,0), more than .page .title.

Main differences from Sass:

  • Native nesting runs in the browser, not at build time. The browser must support it.
  • You cannot build names by gluing text onto &, such as &-title or &__item. In native CSS, & is a selector, not a string.
  • Because of the :is() behaviour, a nested comma list can have specificity different from the Sass output.

The card gets a bold navy title and a yellow background. The card inside .dark takes the light text and dark background. The nested @media gives 24px padding from a 600px viewport. The note is red: #panel .note has a higher score than .page .note.

Keep nesting shallow, around two or three levels. Deep nesting creates long, high-specificity selectors that are hard to override and bring back the problems that flat CSS avoids. Nesting is also a newer feature, so check the support table for your audience, or compile it down with a build tool if you must support older browsers.

html
<style>
  .card {
    padding: 12px;
    border: 1px solid #999;
    color: #222;

    & .title { font-weight: bold; color: navy; }
    &:hover { border-color: crimson; }
    &.featured { background: #fff7d6; }
    .dark & { color: #eee; background: #222; }

    @media (min-width: 600px) { padding: 24px; }
  }

  #panel { .note { color: red; } }
  .page .note { color: blue; }
</style>
<div class="card featured" id="c"><span class="title" id="t">Notice</span></div>
<div class="dark"><div class="card" id="d">Dark card</div></div>
<div id="panel" class="page"><span class="note" id="n">Note</span></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

  • & represents the parent selector: &:hover, &.active, .dark &.
  • @media and @container can be nested inside a rule.
  • Nested rules take the specificity of the parent, like :is().
  • &-suffix name building from Sass is not valid native CSS.
  • Keep nesting shallow to avoid long, high-specificity selectors.

Common mistakes

  • writing &-title expecting BEM-style name building as in Sass. Native CSS does not support this.
  • forgetting that a nested rule's specificity includes the parent. Nesting inside an id selector makes every inner rule hard to override.

Follow-ups

  • when can you omit &?
  • Is native nesting handled by the browser or by a build step?
  • How does a nested rule's specificity compare to the same rule written flat?

Tips

  • Nest by relationship (state, modifier, context), not by markup depth. One level for hover and modifiers is usually enough.
  • Say that you nest by relationship such as state and context, not by markup depth.
  • Name the specificity effect of nesting under an id.
44.html-css-0044Hardsenior

What are container queries, and when would you use them instead of media queries?

A container query applies styles based on the size of a containing element, not the viewport. You mark an ancestor with container-type (usually inline-size), then write @container rules that style its descendants. This suits reusable components that appear in wide and narrow spaces. Media queries still suit page-level decisions.

Full answer

A media query asks about the viewport. A container query asks about the size of a containing element. That matches how component libraries work: a card might sit in a wide main column in one place and a narrow sidebar in another, on the same screen. A media query cannot tell the difference, but a container query can.

To use one, mark an ancestor as a query container with container-type. inline-size is the common value and tracks the width. Optionally name it with container-name, or use the shorthand container: card / inline-size. Then write @container card (min-width: 400px) { ... }. The query applies to descendants of the container, never to the container itself.

Setting container-type: inline-size applies size containment on the inline axis. The container's width then cannot depend on its content, so it needs to get its width from its parent or a CSS value. This avoids loops between size and style.

Container query length units, such as cqw (1 percent of the container's width), size things relative to the container.

The same .card markup shows a stacked layout in the 300px slot and a row layout in the 600px slot, on one page with one viewport width. Use media queries for page-level decisions, such as moving the whole sidebar or switching navigation style. Use container queries for reusable components.

Check the support table for the oldest browsers you serve. A reasonable fallback is to write the base layout so it is acceptable on its own, then enhance with the query.

html
<style>
  body { margin: 0; font-family: sans-serif; }
  .slot { container: card / inline-size; margin-bottom: 12px; border: 1px dashed #999; }
  .card { display: flex; flex-direction: column; gap: 8px; padding: 12px; background: #eef; }
  .thumb { width: 100%; height: 40px; background: #99c; }
  @container card (min-width: 400px) {
    .card { flex-direction: row; align-items: center; }
    .thumb { width: 120px; flex: none; }
  }
</style>
<div class="slot" id="narrow" style="width: 300px"><div class="card" id="c1"><div class="thumb"></div><p>Intro to Python</p></div></div>
<div class="slot" id="wide" style="width: 600px"><div class="card" id="c2"><div class="thumb"></div><p>Intro to Python</p></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

  • container-type: inline-size makes an element a query container for width.
  • @container rules affect descendants, never the container itself.
  • Container size cannot depend on its children's inline size.
  • cqw and related units are relative to the container.
  • Use media queries for page layout and container queries for components.

Common mistakes

  • forgetting container-type. Without it, the @container rule never matches anything.
  • trying to style the container itself inside its own @container block. Only descendants are affected, so add a wrapper inside.

Follow-ups

  • can a container query check more than width?
  • Why can a container not be styled by its own @container rule?
  • What is the difference between container-type: size and inline-size?

Tips

  • Query the smallest useful container, not the page. The component stays reusable if it only cares about its own space.
  • Use the card in a main column versus a sidebar as your example. It is clear and common.
  • Say you give the base layout a working default before enhancing with the query.
45.html-css-0045Hardsenior

A sticky element does not stick. How do you debug it?

position: sticky fails when there is no offset such as top, when an ancestor with overflow hidden, auto or scroll becomes the scroll container, when the parent leaves no room to move, or when a flex item is stretched to the full row height. Walk up the ancestors and check each one's overflow in DevTools.

Full answer

position: sticky behaves like relative until the scroll position reaches a threshold, then it sticks, but only inside its containing block and only relative to its nearest scroll container. Most failures come from one of these causes.

  1. No threshold. Sticky needs at least one of top, bottom, inset-inline-start and so on. Without it, it never sticks.
  2. An ancestor has overflow set to hidden, auto or scroll. That ancestor becomes the scroll container for the sticky element, and if it does not scroll, nothing ever sticks. This is the most common cause.
  3. No room to move. The sticky box can only move inside its parent. If the parent is exactly as tall as the sticky element, there is nothing to travel through.
  4. Flex stretch. In a flex row, items stretch to the row height by default, so a sidebar becomes as tall as its row and has no room to move. Use align-self: flex-start.
  5. A threshold that is hidden behind another fixed header, so it sticks but sits under it. Set top to the header's height.

The test page puts each case in its own scroll box with a height of 150px, scrolls 100px, and compares positions.

After scrolling each box by 100px, the bar in the first box is still at the top of its box. In the second box it scrolled away, because the overflow: hidden wrapper took over as the scroll container. The third (stretched) sidebar also scrolled away, because it filled the row. The fourth, with align-self: flex-start, sticks.

In DevTools, walk up the ancestors of the sticky element and look at each computed overflow value. That finds cause two in a few seconds.

html
<style>
  body { margin: 0; }
  .scroller { height: 150px; overflow: auto; margin-bottom: 8px; border: 1px solid #999; }
  .bar { position: sticky; top: 0; background: gold; height: 24px; }
  .long { height: 400px; background: linear-gradient(#eee, #ccc); }
  .wrap { overflow: hidden; }
  .row { display: flex; }
  .aside { position: sticky; top: 0; background: gold; height: 24px; width: 60px; }
  .row.fixed .aside { align-self: flex-start; }
  .aside.stretch { height: auto; }
</style>
<div class="scroller" id="s1"><div class="bar" id="b1">Works</div><div class="long"></div></div>
<div class="scroller" id="s2"><div class="wrap"><div class="bar" id="b2">Overflow ancestor</div><div class="long"></div></div></div>
<div class="scroller" id="s3"><div class="row"><div class="aside stretch" id="b3">Stretched</div><div class="long" style="flex:1"></div></div></div>
<div class="scroller" id="s4"><div class="row fixed"><div class="aside" id="b4">Fixed</div><div class="long" style="flex:1"></div></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

  • Sticky needs a threshold such as top: 0.
  • An ancestor with overflow other than visible becomes the scroll container.
  • The element only moves inside its parent's box, so the parent must be taller.
  • In a flex row, set align-self: flex-start so the item is not stretched.
  • overflow: clip does not create a scroll container.

Common mistakes

  • setting position: sticky on a table row. Sticky on table parts depends on the browser and the table layout, so test it. Applying it to th cells is the usual approach.
  • giving sticky elements a top of 0 when a fixed header sits above. They stick under the header. Use the header height or a custom property for the offset.

Follow-ups

  • relative to what does sticky stick?
  • Relative to what does sticky stick?
  • How would you make a table header sticky?

Tips

  • Check for overflow on ancestors first. A single overflow-x: hidden added to stop a horizontal scrollbar is the usual culprit. overflow: clip does not create a scroll container and can replace it.
  • Present the five causes as a checklist in a fixed order, with overflow on ancestors first.
  • Mention the fixed header offset case at the end.
46.html-css-0046Hardsenior

How does the browser render a page, and how do you reduce rendering cost in CSS?

The browser runs style, layout, paint and composite. Changes to geometry force layout, appearance changes force paint, and transform or opacity on their own layer can often skip both. To reduce cost, animate transform and opacity, batch DOM reads before writes, use content-visibility: auto and contain, and measure in the Performance panel before changing anything.

Full answer

After parsing, the browser turns HTML and CSS into pixels through a pipeline: style (work out which rules apply), layout (compute size and position of every box), paint (draw boxes into layers) and composite (put the layers together on screen). A change at an early stage usually forces the later stages again.

  • A change to geometry (width, height, margin, top, font size, content) forces layout, then paint and composite.
  • A change that only affects appearance (colour, background, box-shadow) skips layout but still needs paint and composite.
  • A change to transform or opacity on an element with its own layer can often skip layout and paint and only composite. Whether that happens depends on the browser, so verify.

Ways to cut cost:

  • Animate transform and opacity instead of layout properties.
  • Avoid layout thrashing in scripts. Reading a layout value (offsetHeight) right after writing styles forces the browser to compute layout immediately. Batch all reads first, then all writes.
  • Use content-visibility: auto on long off-screen sections so the browser skips their rendering until needed. Pair it with contain-intrinsic-size so the scrollbar stays steady.
  • Use contain to tell the browser that a component's layout and paint do not affect the rest of the page.
  • Keep the DOM small and selectors simple.
  • Use will-change sparingly and for a short time, since each hinted layer uses memory.

While the section is far below the viewport, content-visibility: auto skips its rendering, and its height is the 300px placeholder. After scrolling there, it renders at its true 1000px height. The script reads and then writes, so the browser computes layout once for reading, and the boxes end up 200px wide each.

Measure before optimising. The Performance panel in DevTools shows time in recalculate style, layout, paint and composite, and which of them a given interaction triggers.

html
<style>
  body { margin: 0; }
  .spacer { height: 2000px; }
  .section { content-visibility: auto; contain-intrinsic-size: auto 300px; }
  .section .inner { height: 1000px; background: #eef; }
  .box { width: 100px; height: 20px; background: tomato; margin-bottom: 4px; }
</style>
<div class="spacer"></div>
<section class="section" id="s1"><div class="inner"></div></section>
<div id="boxes"><div class="box"></div><div class="box"></div><div class="box"></div></div>
<script>
  // Batched: read all heights first, then write.
  const boxes = [...document.querySelectorAll(".box")];
  const widths = boxes.map(b => b.offsetWidth);          // reads
  boxes.forEach((b, i) => { b.style.width = widths[i] * 2 + "px"; }); // writes
  document.title = boxes.map(b => b.offsetWidth).join(",");
</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

  • Pipeline: style, layout, paint, composite.
  • Geometry changes trigger layout; colour changes trigger paint; transform and opacity can be composite-only.
  • Layout thrashing comes from alternating style writes and layout reads.
  • content-visibility: auto skips rendering of off-screen sections.
  • Measure first; do not guess.

Common mistakes

  • loops that alternate element.style.width = ... and element.offsetWidth reads. Each read forces a fresh layout. Do all reads first, then all writes.
  • adding will-change: transform to many elements permanently. Extra layers cost memory and can slow things down.

Follow-ups

  • does content-visibility: auto help accessibility?
  • What is layout thrashing and how do you avoid it?
  • What does contain-intrinsic-size do together with content-visibility?

Tips

  • Fix what you measured, not what you guessed. A page with 20ms of layout and 2ms of paint should not get paint tweaks first.
  • Name the stage a property triggers when you recommend a change. It shows you know why.
  • Describe how you would find the slow part in the Performance panel.
47.html-css-0047Hardsenior

How do you keep CSS maintainable and avoid specificity wars in a large codebase?

Specificity wars start when overriding needs longer selectors or !important. Keep most selectors single classes with a naming scheme such as BEM, avoid ids and tag-qualified selectors, put resets behind :where(), order styles with cascade layers, use custom properties as variant inputs, limit !important and lint for specificity.

Full answer

Specificity wars start when one rule needs to beat another and the only tool in reach is a longer selector, an id or !important. Each override raises the bar for the next one. The fix is to design so that most selectors have the same, low specificity, and so that override order is deliberate.

Practices that work in large projects:

  • Style with single classes. A naming scheme such as BEM (.card, .card__title, .card--featured) gives every part a flat selector of one class.
  • Avoid ids and avoid qualifying selectors by tag (div.card). Both raise specificity without benefit.
  • Keep defaults and resets at zero specificity with :where(), so any class overrides them.
  • Order stylesheets from generic to specific: tokens and resets, base elements, components, then utilities. Cascade layers make this order explicit and independent of file order.
  • Use custom properties as the configuration surface, so a variant changes a variable, not a whole set of declarations.
  • Limit !important to a few utility classes where it is the point, and lint for specificity and id selectors with a tool such as Stylelint.
  • Delete dead CSS and keep component styles near the component.

The danger button changes one variable, so it becomes red without a new set of rules. The base link colour sits behind :where() and is overridden by .link-override without any force, even though the override comes from an unlayered rule. The utility mt-0 wins over base margins because its layer is later.

When a conflict appears, resist the urge to lengthen the selector. Ask which of the two rules should rank higher by design, and then move that rule to a layer or reorder instead.

html
<style>
  @layer base, components, utilities;

  @layer base {
    :where(p, li) { line-height: 1.5; margin: 0 0 0.5rem; }
    :where(.prose) a { color: #0a6cff; }
  }
  @layer components {
    .btn {
      --btn-bg: #0a6cff;
      padding: 0.5rem 1rem; border: 0; border-radius: 4px;
      background: var(--btn-bg); color: #fff;
    }
    .btn--danger { --btn-bg: crimson; }
    .btn--small { padding: 0.25rem 0.5rem; }
  }
  @layer utilities {
    .mt-0 { margin-top: 0; }
  }
</style>
<div class="prose">
  <p id="p">A paragraph with a <a href="#" id="link">link</a>.</p>
  <a href="#" class="link-override" id="link2">Another link</a>
</div>
<button class="btn btn--danger btn--small mt-0" id="btn">Delete</button>
<style>
  .link-override { color: green; }
</style>

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

  • Prefer flat, single-class selectors with a naming scheme such as BEM.
  • Keep resets at zero specificity with :where().
  • Use layers to define override order on purpose.
  • Use custom properties so variants change a value, not a whole rule.
  • Limit !important and lint for ids and high specificity.

Common mistakes

  • styling a component by its position in the page (.sidebar .card h3). The same component then looks different elsewhere, and overrides need longer selectors.
  • copying one-off fixes into the global file. They collect over time and no one knows which are still needed.

Follow-ups

  • BEM, utility classes or CSS modules?
  • BEM, utility classes or CSS modules: how do you choose?
  • How do you remove dead CSS safely?

Tips

  • Treat !important as a debt. If you need it to beat your own CSS, the structure needs fixing.
  • Say that you decide which rule should win by design, then move it, rather than lengthening a selector.
  • Choose one convention per project and enforce it with a linter.
48.html-css-0048Hardsenior

How does the native dialog element handle modals, focus and stacking compared with a custom div modal?

The dialog element opened with showModal() renders in the top layer above everything, makes the rest of the page inert, moves focus in and returns it on close, closes on Escape and offers a ::backdrop. A custom div modal must rebuild all of this. show() opens a non-modal dialog.

Full answer

The dialog element is the built-in way to build modals. Calling dialog.showModal() opens it as a modal, and the browser takes care of work that custom modals usually get wrong.

  • Top layer: a modal dialog is rendered in the browser's top layer, above all other content, regardless of z-index or the stacking contexts of its ancestors. You do not need to move it to the end of body.
  • Inert background: the rest of the page cannot be focused or clicked while the modal is open.
  • Focus: focus moves into the dialog on open (to the first focusable element or one with autofocus) and returns to the element that opened it when the dialog closes.
  • Keyboard: the Escape key closes it and fires a cancel event first, which you can intercept.
  • ::backdrop: a pseudo-element you style for the dimmed layer behind the dialog.
  • Semantics: it exposes the dialog role. Give it a name with aria-labelledby.
  • method="dialog" on a form inside it closes the dialog when submitted, and puts the clicked button's value into dialog.returnValue.

dialog.show() opens a non-modal dialog, which does not block the page. Use showModal() for a true modal.

After the click, the dialog is open and matches :modal. Focus moves inside it, and the dialog is on top even though the opener has z-index: 99999. Clicking Delete closes the dialog, sets returnValue to confirm, and focus returns to the opener.

Things the browser does not do for you: the page behind the dialog can still scroll in some setups (set overflow: hidden on the body while open if you need to prevent it), and you must write your own close button text, labels and animations. Animating open and close needs extra care, because the dialog is removed from rendering when closed.

html
<style>
  dialog { border: 0; border-radius: 8px; padding: 1rem; max-width: 20rem; }
  dialog::backdrop { background: rgba(0, 0, 0, 0.5); }
  .high { position: relative; z-index: 99999; }
</style>
<button id="open" class="high" type="button">Delete course</button>
<dialog id="dlg" aria-labelledby="dlg-title">
  <h2 id="dlg-title">Delete this course?</h2>
  <p>This cannot be undone.</p>
  <form method="dialog">
    <button value="cancel" id="cancel">Cancel</button>
    <button value="confirm" id="confirm">Delete</button>
  </form>
</dialog>
<script>
  const dlg = document.getElementById("dlg");
  document.getElementById("open").addEventListener("click", () => dlg.showModal());
  dlg.addEventListener("close", () => { document.title = "closed:" + dlg.returnValue; });
</script>

Checked by clicking the button, reading elementFromPoint at the centre of the viewport, closing with the Delete button, and closing with the Escape key. 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

  • showModal() puts the dialog in the top layer regardless of z-index.
  • The background becomes inert while the modal is open.
  • Focus moves in on open and returns to the opener on close.
  • Escape fires a cancel event and closes it; ::backdrop styles the overlay.
  • Give the dialog an accessible name and a visible close button.

Common mistakes

  • using show() and expecting a modal. show() leaves the page interactive and gives no backdrop or focus handling.
  • building a modal from div elements without focus trapping or an inert background, so keyboard users can tab behind it.

Follow-ups

  • how do you close the dialog when the user clicks the backdrop?
  • How do you close the dialog when the backdrop is clicked?
  • What does a form with method="dialog" do?

Tips

  • Always give the dialog an accessible name and a visible way to close it. Do not rely on Escape alone, since touch users have no Escape key.
  • List what you would otherwise have to write yourself: stacking, focus trap, Escape, restore focus.
  • Mention that Escape alone is not enough for touch users.
49.html-css-0049Hardsenior

How do you build fluid typography with clamp(), and why avoid sizing text with vw alone?

clamp(min, preferred, max) keeps a value between limits. For fluid text, the preferred value mixes a rem part with a vw part, so size grows smoothly between two viewport widths. Using vw alone ignores zoom and user font settings, so use rem limits and test at 200 percent zoom.

Full answer

clamp(min, preferred, max) returns the preferred value, but never below the minimum and never above the maximum. For fluid type, the preferred value mixes a rem part and a vw part, so text grows smoothly with the viewport between two limits, with no breakpoints.

Why not use vw alone? Text sized only in vw does not respond to the browser's zoom or to the user's font size setting in the same way, because the viewport width stays the same. A person with low vision who zooms the page may see no increase. Accessibility guidelines require that text can be enlarged to 200 percent. Adding a rem term to the preferred value, and using rem limits, keeps the text responsive to user settings.

To go from 16px at a 320px viewport to 24px at 1200px, compute the line size = slope * viewport + intercept.

  • slope = (24 - 16) / (1200 - 320) = 0.00909 per px, which is 0.909vw
  • intercept = 16 - 0.00909 * 320 = 13.09px, which is 0.818rem (at 16px per rem)

With a root font size of 16px, the heading is 16px at a 320px viewport, about 20px at 760px, and 24px at 1200px and above. The result is checked in Chrome for each width.

Keep line-height unitless so it scales with each size, and limit line length with ch. A common range is 45 to 75 characters. If you choose limits, use rem for both, so a user's larger default font size scales them, and test the layout with browser zoom at 200 percent.

html
<style>
  body { margin: 0; font-family: Georgia, serif; }
  h1 { font-size: clamp(1rem, 0.818rem + 0.909vw, 1.5rem); line-height: 1.3; }
  p  { max-width: 65ch; line-height: 1.6; }
</style>
<h1 id="h">Fluid heading</h1>
<p>Lines of body text stay near sixty-five characters wide so they are easy to read.</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

  • clamp(min, preferred, max) bounds a value.
  • Preferred value = intercept in rem + slope in vw.
  • vw-only text can fail zoom and user font-size settings.
  • Use rem for limits so default font size changes still apply.
  • Combine with unitless line-height and ch-based line length.

Common mistakes

  • font-size: 4vw with no limits. The text becomes tiny on phones and enormous on wide monitors.
  • using px limits in clamp(). They ignore the user's chosen default font size, so only rem limits respect it.

Follow-ups

  • can clamp() be used for things other than font size?
  • Can clamp() be used for spacing as well?
  • What does line-height with a unitless value do when font size changes?

Tips

  • Use a small helper (a Sass function, a build script or a calculator) to generate clamp() values, and write them as tokens such as --step-1.
  • Show the derivation: slope from the two sizes and viewport widths, then intercept.
  • Mention testing at 200 percent browser zoom.
50.html-css-0050Hardsenior

How do aspect-ratio, image dimensions and reserved space prevent layout shift?

Layout shift happens when the browser did not know a box's final size at first layout. Set width and height attributes on images, use aspect-ratio for embeds and placeholders, reserve space for late content, avoid inserting banners above content, and match fallback fonts. Cumulative Layout Shift measures the effect.

Full answer

Layout shift happens when content already on screen moves because something above or around it changed size, for example an image that finishes loading, an ad slot that fills, or a web font that swaps in. Cumulative Layout Shift (CLS) is a Core Web Vitals metric that scores it. The cause is nearly always that the browser did not know the final size when it first laid out the page.

The fix is to tell the browser the size or the shape in advance.

  • Images and video: set width and height attributes that match the file's pixel size. Browsers use them to compute an aspect ratio before the file arrives, so with max-width: 100%; height: auto in CSS, the box has the right height straight away.
  • Any box that will get content later (embeds, maps, cards with images): use CSS aspect-ratio, for example aspect-ratio: 16 / 9, or a min-height.
  • Banners and notices: reserve their space, or insert them below the current viewport. Do not push content down after the user starts reading.
  • Fonts: choose font-display carefully, preload key fonts, and use a fallback with similar metrics so the swap does not reflow text. size-adjust and related descriptors in @font-face help match them.
  • Animations: change transform, not top or height.

In a 400px column, the photo is 200px high (600 by 300 scaled down), the embed placeholder is 225px high (400 divided by 16 and times 9) before any video loads, and the thumbnail is a 100px square with its picture cropped by object-fit: cover.

To find shifts, open the Performance panel and look at the layout shift entries, or use PerformanceObserver with the layout-shift entry type. Chrome's Lighthouse reports CLS too. A good target is a CLS of 0.1 or less.

html
<style>
  body { margin: 0; width: 400px; font-family: sans-serif; }
  img { max-width: 100%; height: auto; display: block; }
  .embed { aspect-ratio: 16 / 9; background: #333; color: #fff; }
  .thumb { aspect-ratio: 1; width: 100px; object-fit: cover; }
</style>
<img id="photo" width="600" height="300" alt="Campus"
     src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='600' height='300'%3E%3Crect width='600' height='300' fill='%2399ccff'/%3E%3C/svg%3E">
<div class="embed" id="embed">Video placeholder</div>
<img class="thumb" id="thumb" width="300" height="200" alt="Lab"
     src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='300' height='200'%3E%3Crect width='300' height='200' fill='%23cc99ff'/%3E%3C/svg%3E">

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

  • Cause: content arrives after layout and pushes other content.
  • width and height attributes give images an aspect ratio before loading.
  • aspect-ratio reserves space for embeds and placeholders.
  • Reserve space for ads and banners; do not insert above what the user reads.
  • Check shifts in the Performance panel or with a layout-shift observer.

Common mistakes

  • setting an image's CSS to width: 100%; height: 300px with no regard for the ratio. The image is then stretched or the layout is wrong at some screen widths.
  • lazy-loading the image at the very top of the page. Above-the-fold images should load early. Lazy-load the ones below.

Follow-ups

  • does CSS aspect-ratio replace the width and height attributes on img?
  • How do web fonts cause layout shift and what reduces it?
  • Why should above-the-fold images not be lazy-loaded?

Tips

  • Make width and height attributes part of the image component, so every image reserves space without anyone remembering.
  • Say the metric (CLS) and its target of 0.1 or less, then the fixes in order of how often they matter.
  • Describe one example from images and one from fonts.
51.html-css-0051Hardsenior

How do you build light and dark themes with custom properties, color-scheme and prefers-color-scheme?

Define colours as custom properties, redefine them for dark mode under prefers-color-scheme, set color-scheme so built-in controls follow, and add a data-theme attribute for a manual override. Set the saved theme from an inline script in the head to avoid a flash. Check contrast in both themes.

Full answer

A theme is a set of design tokens, such as text colour and background, kept in custom properties. Components use var(--bg) and var(--text) and never hard-code colours. Switching the theme means redefining those variables in one place.

Three pieces work together:

  1. prefers-color-scheme is a media feature that tells you the operating system or browser preference (light or dark). Use it to define dark values by default.
  2. color-scheme: light dark on :root tells the browser the page supports both, so built-in parts (form controls, scrollbars, default page background) also switch.
  3. A manual override. Users often want to pick a theme independent of the system. Store the choice (for example in localStorage) and write it as an attribute such as data-theme="dark" on html. Your CSS then follows the attribute first and the system preference second.

To avoid a flash of the wrong theme on load, set the attribute from a tiny inline script in the head, before the first paint.

With a light system setting, the page shows dark text on white. With a dark system setting it switches to light text on a dark background. If data-theme="light" is set, the page stays light even on a dark system, and data-theme="dark" forces dark on a light system. A theme toggle only needs to set the attribute and save the choice.

Check colour contrast in both themes, not only the default. Shadows, images with white backgrounds and borders often need dark variants. A newer CSS function, light-dark(), can write both values on one line, but check support before depending on it.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Theme demo</title>
  <script>
    const saved = localStorage.getItem("theme");
    if (saved) document.documentElement.dataset.theme = saved;
  </script>
  <style>
    :root { color-scheme: light dark; --bg: #ffffff; --text: #1a1a1a; --accent: #0a6cff; }
    @media (prefers-color-scheme: dark) {
      :root:not([data-theme="light"]) { --bg: #121212; --text: #eeeeee; --accent: #7fb2ff; }
    }
    :root[data-theme="dark"]  { color-scheme: dark;  --bg: #121212; --text: #eeeeee; --accent: #7fb2ff; }
    :root[data-theme="light"] { color-scheme: light; }
    body { background: var(--bg); color: var(--text); font-family: sans-serif; }
    a { color: var(--accent); }
  </style>
</head>
<body>
  <p>Hello, <a href="#" id="link">theme</a>.</p>
</body>
</html>

This is a complete page. It was checked with the system scheme set to light and to dark, and with data-theme set to light and to dark.

Key points

  • Use role-named tokens such as --bg and --text.
  • prefers-color-scheme provides the system default.
  • color-scheme: light dark themes scrollbars and form controls.
  • A data-theme attribute on html supports a manual toggle.
  • Set the saved choice before first paint to avoid a flash.

Common mistakes

  • forgetting color-scheme. The page itself is themed, but the scrollbar, form controls and default text boxes stay light.
  • reading the saved theme after the page renders, which flashes the wrong colours. Set it from an inline script in the head.

Follow-ups

  • how do you read the system preference from JavaScript?
  • How do you read the system colour scheme in JavaScript?
  • What does light-dark() do, and what should you check before using it?

Tips

  • Name tokens by role (--bg, --text, --border) and never by colour (--white). A dark theme then does not have to lie about names.
  • Describe the three layers: tokens, system preference, manual override.
  • Mention checking contrast in both themes.
52.html-css-0052Easyfresher

Which metadata tags belong in the head of a page, and what does each one do?

The head contains metadata for browsers, search engines and sharing apps. Key tags are charset, viewport, a unique title, a description, a canonical link and Open Graph tags. The lang attribute on html declares the page language.

Full answer

The head holds information about the page. Visitors do not see it on the page, but browsers, search engines and chat apps read it.

  • meta charset="utf-8" tells the browser how to decode the text. Put it first, within the first 1024 bytes of the file.
  • title is the name shown in the tab, in bookmarks and in search results. Give every page its own title, and put the most specific words first.
  • meta name="description" is a short summary. Search engines may show it under the title. About 150 to 160 characters is a common guide, because longer text is often cut off. It is not a ranking factor, but a good one earns more clicks.
  • meta name="viewport" makes layout use the real device width on phones.
  • link rel="canonical" names the preferred address when the same content is reachable at several URLs, such as with and without tracking parameters.
  • Open Graph tags (og:title, og:description, og:image) control the preview card when the link is shared in a chat or social app.
  • meta name="robots" content="noindex" asks search engines not to list the page, for example for a thank-you page.
  • lang on the html element states the page language. It helps screen readers pick a voice and helps translation tools.

In this page the description is under 160 characters, the canonical address is an absolute URL, and the language is declared. Social and search previews depend on the crawlers that read these tags, so test a real link in the sharing tools you care about.

Use one unique title and description per page. Repeating the same ones across many pages makes search results look the same and wastes the space.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>CSS Flexbox Practice Questions | Schoolabe</title>
  <meta name="description" content="Practise flexbox with ten interview-style questions, short answers and runnable examples for freshers and experienced developers.">
  <link rel="canonical" href="https://schoolabe.com/interview-prep/html-css/flexbox">
  <meta property="og:title" content="CSS Flexbox Practice Questions">
  <meta property="og:description" content="Ten flexbox questions with runnable examples.">
  <meta property="og:image" content="https://schoolabe.com/images/flexbox-card.png">
  <meta property="og:url" content="https://schoolabe.com/interview-prep/html-css/flexbox">
  <link rel="icon" href="/favicon.ico">
</head>
<body>
  <h1>Flexbox practice</h1>
</body>
</html>

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

  • charset utf-8 goes first so the browser decodes the rest correctly.
  • Each page needs its own title and description.
  • canonical names the preferred URL when content is reachable at several addresses.
  • Open Graph tags control the preview card when a link is shared.
  • lang on the html element helps screen readers and translation tools.

Common mistakes

  • Leaving out the description and letting the search engine pick random text from the page.
  • Using the same title on every page, such as the site name only.
  • Using a relative URL in og:image or canonical. Crawlers need the full absolute address.

Follow-ups

  • What does the canonical link tell a search engine?
  • Why should the charset declaration come first in the head?

Tips

  • Write the tags for one real page in your head, with a title under about 60 characters and a description near 150. It is a common live task.
  • Mention noindex and canonical when asked about duplicate or private pages. They show you know what the head is for.
53.html-css-0053Easyfresher

How should heading levels h1 to h6 be used on a page?

Headings form the outline of a page. Use one h1 for the page title, h2 for main sections and h3 to h6 for parts inside them, without skipping levels downwards. Choose the level for structure and use CSS for size.

Full answer

Headings give a page an outline. h1 is the main title, h2 marks the major sections, h3 the parts inside a section, and so on down to h6. Think of the contents page of a textbook: chapter, topic, sub-topic.

Rules that work well in practice:

  • Use one h1 that names the page. The HTML specification allows more than one, but a single h1 gives the clearest outline for people and tools.
  • Do not skip levels going down. An h3 directly after an h1 leaves a hole in the outline.
  • Choose a heading level for structure, never for size. If an h2 looks too big, change its CSS.
  • Keep headings short and meaningful, so a list of them reads like a summary.
  • Do not use a heading for text that is only bold or large, such as a price or a quote.

Screen reader users often jump from heading to heading, or open a list of all headings, to find their way. Search engines also read headings to understand what each part is about.

The script prints the order of levels used, reports no skipped levels for this page, and reports h1 to h3 for the broken list [1, 3, 2]. A check like this is easy to add to a test or a linter.

A heading can go up any number of levels, for example from an h3 back to an h2. Only jumping down by more than one level leaves a gap.

html
<main>
  <h1>Web Development Course</h1>
  <h2>Week 1: HTML</h2>
  <h3>Elements and attributes</h3>
  <h3>Forms</h3>
  <h2>Week 2: CSS</h2>
  <h3>The box model</h3>
</main>
<pre id="out"></pre>
<script>
  function skipped(levels) {
    const gaps = [];
    for (let i = 1; i < levels.length; i++) {
      if (levels[i] > levels[i - 1] + 1) gaps.push("h" + levels[i - 1] + " to h" + levels[i]);
    }
    return gaps.length ? gaps.join(", ") : "none";
  }
  const levels = [...document.querySelectorAll("h1,h2,h3,h4,h5,h6")].map(h => Number(h.tagName[1]));
  document.getElementById("out").textContent =
    "outline: " + levels.map(l => "h" + l).join(" > ") + "\n" +
    "skipped on this page: " + skipped(levels) + "\n" +
    "skipped in [1, 3, 2]: " + skipped([1, 3, 2]);
</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

  • h1 names the page; h2 to h6 build the outline below it.
  • Do not skip levels when going down, such as h1 straight to h3.
  • Level is for structure; size belongs to CSS.
  • Screen reader users and search engines both read headings to understand the page.
  • Do not use headings for text that is only bold or large.

Common mistakes

  • Picking h3 or h4 because the default size looks right. Fix the size in CSS and keep the level honest.
  • Using several h1 elements in different parts of the page without a clear reason, which blurs the main topic.
  • Making the logo or the site name the h1 on every page, so every page has the same main heading.

Follow-ups

  • Is it valid to have more than one h1 on a page?
  • How would you automatically detect skipped heading levels?

Tips

  • Describe the outline test: read only the headings and check that the page still makes sense. It is a quick way to review your own page.
  • Mention screen reader heading navigation. It is the practical reason the order matters.
54.html-css-0054Easyfresher

When do you use ul, ol and dl, and which attributes does ol have?

Use ul when order does not matter, ol when it does, and dl for term and description pairs. Only li may be a direct child of ul and ol, and nested lists go inside an li. ol supports start, reversed and type, and CSS controls markers.

Full answer

HTML has three kinds of list.

  • ul is an unordered list. Use it when the order does not matter, such as a list of features or a navigation menu.
  • ol is an ordered list. Use it when the order matters, such as steps in a recipe or a ranking.
  • dl is a description list. It pairs terms (dt) with their descriptions (dd), like a glossary or a set of label and value pairs.

Only li elements may be direct children of ul and ol. To nest a list, place the inner ul or ol inside an li, not beside it.

The ol element has useful attributes: start sets the first number, reversed counts down, and type chooses the marker (1, a, A, i, I). An individual li can take a value to jump to a given number. The look of the marker is a CSS job: list-style-type, list-style-position and list-style: none.

The first list counts 3, 2, 1 because of reversed start="3". The nested ul sits inside the li for Fruit. The navigation uses list-style: none so the bullets disappear, but it is still a list, and screen readers announce "list, 2 items" to help users know what they are entering.

A menu is a list of links, so ul is the right element for it even though it does not look like bullets. Removing the markers with CSS does not change the meaning.

html
<style>
  nav ul { list-style: none; margin: 0; padding: 0; display: flex; gap: 1rem; }
</style>
<ol reversed start="3" id="top3">
  <li>Gold</li>
  <li>Silver</li>
  <li>Bronze</li>
</ol>
<ul>
  <li>Fruit
    <ul><li id="inner">Mango</li></ul>
  </li>
</ul>
<dl>
  <dt>Padding</dt><dd>Space inside the border.</dd>
  <dt>Margin</dt><dd>Space outside the border.</dd>
</dl>
<nav aria-label="Main"><ul><li><a href="/">Home</a></li><li><a href="/fees">Fees</a></li></ul></nav>

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

  • ul is unordered, ol is ordered, dl pairs dt terms with dd descriptions.
  • Direct children of ul and ol must be li elements.
  • Nested lists belong inside an li.
  • ol has start, reversed and type attributes; li can take value.
  • Removing markers with CSS keeps the list semantics.

Common mistakes

  • Putting an inner ul directly inside another ul, outside any li. This is invalid HTML.
  • Using br tags or separate paragraphs to fake a list. Screen readers then do not announce it as a list.
  • Using ol for a list where order does not matter, which suggests a ranking that does not exist.

Follow-ups

  • How do you nest a list inside another list correctly?
  • What is a description list and when would you choose it?

Tips

  • When asked for a menu, say that a ul of links is the usual structure and CSS removes the bullets.
  • Know ol start, reversed and type by heart. They are small details that show hands-on use.
55.html-css-0055Mediummid

How do you add video or audio to a page with captions, and what should you know about autoplay?

Use video or audio with controls, several source files and a track element pointing to a WebVTT file for captions. Add a poster and a transcript for audio. Browsers limit autoplay with sound, so avoid it.

Full answer

The video and audio elements play media without plugins. Add the controls attribute so users get play, pause, volume and seek buttons. Without it, nothing is shown unless you build your own controls.

Offer more than one file with source elements. The browser uses the first file it can play, based on the type. Text between the tags is a fallback for browsers that do not support the element.

Captions and subtitles use the track element with a WebVTT file. kind="captions" includes speaker sounds as well as speech, kind="subtitles" is a translation of speech, and kind="descriptions" describes visuals. Set srclang and a label, and add default to turn one on by default. Captions help deaf and hard-of-hearing viewers, people in noisy places, and learners who read along. Audio-only content should have a transcript on the page.

Other useful attributes: poster is the image shown before play, preload hints how much to download (none, metadata, auto), loop repeats, and playsinline lets video play inside the page on some phones instead of full screen.

Autoplay is limited by browsers. Playback with sound usually needs a user action first, while muted autoplay is generally allowed. Do not autoplay sound, because it surprises users and can make a screen reader hard to hear.

The video has two source files, one captions track in English, and a poster. The audio element downloads nothing until the user presses play, because of preload="none", and the transcript link serves people who cannot listen.

The file names in this example are placeholders, so use your own files when you try it.

html
<video id="lesson" controls preload="metadata" width="480" poster="lesson-poster.jpg">
  <source src="lesson.webm" type="video/webm">
  <source src="lesson.mp4" type="video/mp4">
  <track kind="captions" src="lesson.en.vtt" srclang="en" label="English" default>
  <p>Your browser cannot play this video. <a href="lesson.mp4">Download it</a>.</p>
</video>
<audio id="podcast" controls preload="none" src="episode-1.mp3"></audio>
<p><a href="/episode-1-transcript">Read the transcript of episode 1</a></p>

The media files and the caption file are placeholders. A local test server returned an empty body for the video and a small caption file for the track, so the check read the track elements and their attributes, not playback. 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

  • controls gives users play, pause, volume and seek.
  • Several source elements let the browser pick a format it can play.
  • track with kind, srclang, label and a WebVTT file adds captions or subtitles.
  • poster, preload and playsinline control the first impression and data use.
  • Audio needs a transcript on the page.

Common mistakes

  • Skipping captions because the page already has a transcript. Both help, and captions are expected for video.
  • Autoplaying with sound. Browsers often block it and users dislike it.
  • Forgetting the type attribute on source, so the browser downloads parts of files to find out if it can play them.

Follow-ups

  • What is the difference between captions and subtitles?
  • Why does muted autoplay usually work while autoplay with sound is blocked?

Tips

  • Name the kinds of track (captions, subtitles, descriptions) and the file format (WebVTT) in your answer.
  • Mention preload="metadata" or "none" to save data on pages with many media files.
56.html-css-0056Mediummid

How do loading="lazy", decoding and fetchpriority help page speed, and where should you not use them?

loading="lazy" delays images and iframes until they are near the viewport, decoding="async" lets decoding happen off the critical path, and fetchpriority raises or lowers a request's priority. Use lazy only below the fold and keep width and height set.

Full answer

Not every image on a page is needed at once. Images far below the visible area can wait until the user scrolls near them. That saves data and leaves bandwidth for what matters first.

  • loading="lazy" on img and iframe tells the browser to delay fetching until the element is close to the viewport. The browser decides how close, and the distance differs between browsers and connections. The default is eager.
  • decoding="async" allows the browser to decode the image without blocking other rendering. It does not change when the file is fetched.
  • fetchpriority="high" raises the priority of one important request, usually the main image at the top of the page, which is often the largest contentful paint element. fetchpriority="low" lowers it for less important images.

Never lazy-load the image the user sees first. Delaying it makes the main content appear later and hurts the Largest Contentful Paint. Also keep width and height on every image. A lazy image with no reserved space makes the page jump when it loads.

The hero image loads straight away with high priority. The gallery image is 6000px down, so it is not fetched until the user scrolls near it. In Chrome the image reports complete as false at first and true after scrolling to it. The map iframe also waits.

The default distance threshold is large on purpose, so images are ready before the user reaches them. Treat lazy loading as a hint, and check the Network panel to confirm what really loads on first paint.

html
<style>
  body { margin: 0; }
  .spacer { height: 6000px; background: linear-gradient(#fff, #ddd); }
</style>
<img id="hero" src="hero.jpg" width="800" height="400" alt="Students in a lab" fetchpriority="high">
<div class="spacer"></div>
<img id="below" src="gallery-1.jpg" width="800" height="400" alt="Library reading room" loading="lazy" decoding="async">
<iframe id="map" src="https://example.com/map" width="400" height="200" title="Campus map" loading="lazy"></iframe>

The image files are placeholders served by a local test server. The check read the attributes and confirmed that a lazy image below the fold was still not loaded before scrolling and loaded after scrolling. Real download timing was not measured. 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

  • loading="lazy" delays offscreen images and iframes; eager is the default.
  • Do not lazy-load the first visible image.
  • fetchpriority="high" should go on one or two key requests only.
  • decoding="async" affects decoding, not fetching.
  • Width and height prevent layout shift for lazy images.

Common mistakes

  • Adding loading="lazy" to the hero image. It delays the most important image on the page.
  • Lazy-loading without width and height, so the layout shifts when each image appears.
  • Using fetchpriority="high" on many images. If everything is high priority, nothing is.

Follow-ups

  • Which Core Web Vital can lazy-loading the first image make worse?
  • Does decoding="async" delay the download of an image?

Tips

  • Say the rule in one line: eager for what the user sees first, lazy for the rest.
  • Check the Network panel with a throttled connection and a short screen to see what loads at first paint.
57.html-css-0057Easyfresher

Which color formats does CSS support, and how do you choose between hex, rgb() and hsl()?

CSS supports named colors, hex, rgb(), hsl(), transparent and currentColor, and most formats accept an alpha value. hsl() is easy for building shades, hex is compact, and currentColor makes borders and icons follow the text color.

Full answer

CSS accepts several ways to write the same color.

  • Named colors such as tomato or navy. Handy for quick tests.
  • Hex: #ff6347 (red, green, blue in base 16). #f63 is a short form when each pair repeats. #ff634780 adds an alpha (transparency) pair.
  • rgb(): rgb(255 99 71). Add transparency with a slash: rgb(255 99 71 / 50%). The older comma form rgb(255, 99, 71) still works.
  • hsl(): hue (an angle on the colour wheel, 0 to 360), saturation and lightness, as in hsl(9 100% 64%). This is the easiest format to adjust by hand. Keep the hue and raise the lightness for a lighter shade.
  • transparent is fully transparent.
  • currentColor is the element's current text color. It lets borders, SVG icons and shadows follow the text colour automatically.

Choose by purpose. Hex is compact and common in design tools. hsl() is better for building a family of shades. A custom property such as --brand-hue: 9 can feed several hsl() colours. Always check text contrast against its background, whichever format you use.

The first three swatches are the same color written three ways, and the browser reports all of them as rgb(255, 99, 71). The fourth is half transparent. The last two share one hue with different lightness. The underline of the link matches the teal text because of currentColor.

Wide-gamut formats such as oklch() also exist. They are covered in a separate question.

html
<style>
  .swatch { display: inline-block; width: 60px; height: 40px; }
  #a { background: #ff6347; }
  #b { background: rgb(255 99 71); }
  #c { background: tomato; }
  #d { background: rgb(255 99 71 / 50%); }
  .link { color: teal; border-bottom: 2px solid currentColor; }
  :root { --hue: 200; }
  #e { background: hsl(var(--hue) 70% 30%); }
  #f { background: hsl(var(--hue) 70% 80%); }
</style>
<span class="swatch" id="a"></span><span class="swatch" id="b"></span><span class="swatch" id="c"></span>
<span class="swatch" id="d"></span><span class="swatch" id="e"></span><span class="swatch" id="f"></span>
<p><span class="link" id="link">Read more</span></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

  • Hex, rgb() and hsl() can all describe the same color.
  • Alpha adds transparency: #rrggbbaa or rgb(r g b / 50%).
  • hsl() separates hue, saturation and lightness, so shades are easy to adjust.
  • currentColor reuses the element's text color for borders, icons and shadows.
  • Alpha on a color fades only that color; opacity fades the whole element.

Common mistakes

  • Writing a hex color with five digits, or without the leading #. Valid hex has 3, 4, 6 or 8 digits.
  • Using opacity on an element when only the background should be transparent. Opacity fades the text and children too, while an alpha color fades only that color.
  • Picking text and background shades by eye, without checking the contrast ratio.

Follow-ups

  • What is the difference between opacity: 0.5 and a color with 50 percent alpha?
  • How would you build a lighter and a darker shade of a brand color?

Tips

  • Show that you can convert in your head only in simple cases, such as #ff0000 equals rgb(255 0 0). For real work use DevTools' color picker.
  • Mention currentColor for icons. It saves a lot of repeated color values.
58.html-css-0058Easyfresher

How do object-fit and object-position control how an image fills its box?

object-fit tells the browser how to scale an image or video inside a box with a different shape. cover fills and crops, contain fits and leaves empty space, fill stretches, and object-position chooses which part stays visible.

Full answer

When an img or video has a fixed box, for example 100px by 100px, but the file has a different shape, the browser must decide what to do. By default it stretches the picture to fit (object-fit: fill), which distorts it.

object-fit chooses the rule.

  • fill: stretch to the box. This is the default and distorts the picture.
  • contain: scale the picture to fit fully inside the box, keeping its shape. Empty bars may appear on the sides or top and bottom.
  • cover: scale the picture to cover the whole box, keeping its shape. Part of the picture is cropped.
  • none: do not resize. The picture keeps its natural size and is cropped.
  • scale-down: use none or contain, whichever gives the smaller result.

object-position decides which part stays visible when the picture is cropped. The default is 50% 50%, the centre. For a portrait photo in a wide box, object-position: top keeps the faces and crops the legs.

These properties apply to replaced elements, such as img, video and canvas. For a CSS background image, the matching property is background-size.

All three wide pictures sit in a 100 by 100 box. The first is squashed, the second shows the full picture with space above and below, and the third fills the box and crops the right side because of left top. The avatar is a tall photo shown as a round 64px circle, and cover keeps the proportions.

This is the standard pattern for profile pictures and card thumbnails: fix the box size, add object-fit: cover.

html
<style>
  img { width: 100px; height: 100px; border: 1px solid #999; margin-right: 8px; }
  .fill    { object-fit: fill; }
  .contain { object-fit: contain; }
  .cover   { object-fit: cover; object-position: left top; }
  .avatar  { width: 64px; height: 64px; border-radius: 50%; object-fit: cover; }
</style>
<img id="a" class="fill"    alt="Wide banner" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='200'%3E%3Crect width='400' height='200' fill='%2399ccff'/%3E%3C/svg%3E">
<img id="b" class="contain" alt="Wide banner" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='200'%3E%3Crect width='400' height='200' fill='%2399ccff'/%3E%3C/svg%3E">
<img id="c" class="cover"   alt="Wide banner" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='200'%3E%3Crect width='400' height='200' fill='%2399ccff'/%3E%3C/svg%3E">
<img id="d" class="avatar"  alt="Student photo" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='300' height='500'%3E%3Crect width='300' height='500' fill='%23cc99ff'/%3E%3C/svg%3E">

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

  • fill is the default and distorts the picture.
  • cover fills the box and crops; contain shows everything and may leave space.
  • object-position picks the visible part when cropping.
  • It applies to replaced elements such as img and video.
  • background-size is the matching property for background images.

Common mistakes

  • Setting width and height on an image and not setting object-fit, so the picture looks stretched.
  • Using cover and cropping out the important part, for example a face. Adjust object-position.
  • Expecting object-fit to work on a div with a background image. Use background-size there.

Follow-ups

  • What is the background-size equivalent of object-fit: cover?
  • How do you keep the top of a tall photo visible in a wide box?

Tips

  • Explain cover and contain with one sentence each: cover fills and crops, contain fits and leaves space.
  • Pair object-fit: cover with an aspect-ratio or a fixed height so card thumbnails line up.
59.html-css-0059Easyfresher

How do CSS counters number headings and list items without extra markup?

CSS counters keep a running number: counter-reset starts it, counter-increment raises it, and counter() or counters() shows it in a content property. They suit numbered headings, steps and nested outlines.

Full answer

A CSS counter is a number the browser keeps while it reads the page. You decide when it starts, when it goes up, and where it is shown. This is useful for numbered headings, figure captions or steps, because the numbers stay correct when you add or move an item.

Three pieces are involved.

  • counter-reset: name creates or resets a counter on an element. The value starts at 0.
  • counter-increment: name adds 1 (or the amount you give) each time the selector matches.
  • counter(name) shows the current value inside a content property, usually on ::before.

For nested numbering like 1, 1.1, 1.2, use counters(name, "."). Each nested element that resets the counter creates a new level, and counters() joins all levels with the separator.

A built-in alternative is ol with li, which numbers itself. Counters are for cases where you cannot use ol, or where numbers should appear on headings, table rows or steps built from div.

The headings read "1. Install the tools" and "2. Write the page". The step counter restarts after each h2, so the paragraphs read Step 1, Step 2, then Step 1 again. The list prints 1, 1.1, 1.2 and 2.

Generated numbers are not part of the page text. Screen readers may or may not read them, so for important numbering, such as steps, also consider a real ol.

html
<style>
  body { counter-reset: section; }
  h2 { counter-reset: step; }
  h2::before { counter-increment: section; content: counter(section) ". "; }
  .step::before { counter-increment: step; content: "Step " counter(step) ": "; font-weight: bold; }
  ul.tree, ul.tree ul { counter-reset: item; list-style: none; }
  ul.tree li::before { counter-increment: item; content: counters(item, ".") " "; }
</style>
<h2 id="h1">Install the tools</h2>
<p class="step">Download the editor.</p>
<p class="step">Open a new file.</p>
<h2 id="h2">Write the page</h2>
<p class="step">Type the HTML.</p>
<ul class="tree">
  <li>Fruit
    <ul><li>Mango</li><li>Banana</li></ul>
  </li>
  <li>Vegetables</li>
</ul>

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

  • counter-reset creates the counter, counter-increment raises it.
  • counter(name) shows the value in content, usually on ::before.
  • counters(name, separator) joins nested levels, such as 1.2.
  • Resetting on a parent restarts numbering for each section.
  • Generated numbers are not real text, so use ol when meaning matters.

Common mistakes

  • Forgetting counter-reset, so numbering continues from another part of the page.
  • Using counter-increment on the same element that shows it before the reset, so the first number starts at the wrong value.
  • Relying on counter numbers for meaning that screen readers must hear. Generated content support in assistive technology varies.

Follow-ups

  • How is counters() different from counter()?
  • When is a plain ol a better choice than a CSS counter?

Tips

  • Describe the three steps (reset, increment, display) before showing any code.
  • Use counters() with a separator for outlines such as 1.2.3.
60.html-css-0060Easyfresher

How do you truncate long text with an ellipsis on one line or on several lines?

For one line use white-space: nowrap, overflow: hidden and text-overflow: ellipsis. For several lines use -webkit-line-clamp with display: -webkit-box and overflow: hidden. The full text stays in the DOM and only the display is cut.

Full answer

For one line, three properties work together: white-space: nowrap keeps the text on one line, overflow: hidden clips what does not fit, and text-overflow: ellipsis replaces the clipped end with three dots. The element needs a width limit, such as a fixed width, a percentage or a grid or flex cell that can shrink.

For several lines, the common method uses display: -webkit-box, -webkit-box-orient: vertical, -webkit-line-clamp: 2 and overflow: hidden. Despite the prefix, it is the method most sites use. A standard line-clamp property exists, but it is newer, so check the support table before relying on it alone.

The full text is still in the page and still read by screen readers and found by search. Only the display is cut. If users must be able to read the rest, give them a way: a link, a "Read more" button, or an expandable area.

The first paragraph stays on one line and ends in an ellipsis, so its scroll width is larger than its visible width. The second shows two lines of 20px each, so it is 40px tall, even though the text needs more lines.

Inside a flex item, remember to add min-width: 0 to the item so it is allowed to shrink. Without it the text pushes the container wider instead of being clipped.

html
<style>
  body { margin: 0; font: 16px/20px sans-serif; }
  .one {
    width: 200px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .two {
    width: 200px;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
  }
</style>
<p class="one" id="one">Introduction to Data Structures and Algorithms, Lecture Notes for Semester Two</p>
<p class="two" id="two">Introduction to Data Structures and Algorithms, Lecture Notes for Semester Two, including worked examples and practice questions for every chapter.</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

  • Single line needs nowrap, overflow hidden and text-overflow ellipsis.
  • Multi-line uses -webkit-line-clamp with display: -webkit-box and a vertical box orientation.
  • The element needs a width limit for clipping to happen.
  • The full text remains available to screen readers and search.
  • Flex items need min-width: 0 to be clipped.

Common mistakes

  • Forgetting white-space: nowrap for the one-line version, so the text wraps and no ellipsis appears.
  • Truncating important information, such as a price or a date, with no way to read the rest.
  • Applying text-overflow to a flex item without min-width: 0, so the item grows instead of clipping.

Follow-ups

  • Why does text-overflow: ellipsis do nothing on a flex item sometimes?
  • How would you let a user expand a clamped paragraph?

Tips

  • Write the three-line single-line recipe from memory, then add the line-clamp version.
  • Say that truncation changes only what is seen. Screen readers and search still get the full text.