← Interview prep

HTML & CSS interview questions

Semantic HTML, CSS layout, and CSS interview depth.

193 questions · Page 4 of 10

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

Page 4 of 10

Questions 61–80 of 193 · 0 of 20 on this page marked learned

61.html-css-0061Mediummid

How do you style checkboxes, radio buttons and other form controls without breaking accessibility?

accent-color recolours native checkboxes, radios, sliders and progress bars with one line. For full control, appearance: none removes the native drawing, but then you must rebuild checked, focus and disabled states and keep the real input element and its label.

Full answer

Form controls are drawn by the browser, which is why they look different on each system. There are two main ways to restyle them.

The simple way is accent-color. It sets the main colour of checkboxes, radio buttons, range sliders and progress bars. One line gives the control your brand colour, and the browser still draws it, so keyboard behaviour, focus rings and high-contrast modes keep working.

The deeper way is appearance: none, which removes the native drawing. You then paint the control yourself with borders, backgrounds and a pseudo-element for the tick. This gives full control, but you must rebuild what the browser gave you: a visible focus style, a checked and an unchecked look, a disabled look, and enough colour contrast.

Keep the real input element. Do not replace it with a div, because the input already has the right role, keyboard support and form submission. Always keep a label connected to it.

The first checkbox is the native control in the brand colour. The second is drawn by CSS: it has an empty box when unchecked, and a blue background with a tick after the user checks it. Clicking the label toggles it, and a keyboard user sees a clear outline when the box has focus.

Check each state in a screen reader and with forced colours. Custom drawings sometimes disappear there, so keep a visible border.

html
<style>
  .native { accent-color: #0a6cff; }
  .custom {
    appearance: none;
    width: 1.25rem; height: 1.25rem;
    border: 2px solid #444; border-radius: 4px;
    display: inline-grid; place-content: center;
    vertical-align: middle; margin: 0 0.5rem 0 0;
  }
  .custom::before {
    content: ""; width: 0.6rem; height: 0.6rem;
    transform: scale(0); transition: transform 0.1s;
    background: #fff; clip-path: polygon(14% 44%, 0 65%, 50% 100%, 100% 16%, 80% 0, 43% 62%);
  }
  .custom:checked { background: #0a6cff; border-color: #0a6cff; }
  .custom:checked::before { transform: scale(1); }
  .custom:focus-visible { outline: 3px solid #0a6cff; outline-offset: 2px; }
  .custom:disabled { opacity: 0.5; }
</style>
<label><input class="native" type="checkbox" id="n" checked> Email me updates</label>
<label><input class="custom" type="checkbox" id="c"> I accept the terms</label>

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

  • accent-color recolours native controls and keeps their behaviour.
  • appearance: none removes native drawing and gives full control.
  • Rebuild all states: checked, focus-visible, disabled.
  • Keep the real input and its label for keyboard and screen readers.
  • Check contrast and forced-colors mode for custom drawings.

Common mistakes

  • Using appearance: none and forgetting the focus style, so keyboard users cannot see where they are.
  • Hiding the input with display: none and building a fake control from divs. It removes keyboard and screen reader support.
  • Setting a custom checked colour that fails the contrast ratio against the page background.

Follow-ups

  • What does accent-color not change?
  • Why is it better to keep the real input element than to build the control from divs?

Tips

  • Start with accent-color. Say that you only go to appearance: none when the design needs it.
  • Test every state: unchecked, checked, focus, disabled, and forced colours.
62.html-css-0062Easyfresher

When should you use an a element and when a button element?

Use a with href when the control goes somewhere, and button when it does something on the current page. Native elements give focus, keyboard activation and correct announcements for free. A button in a form submits by default, so set type="button" when it should not.

Full answer

Use the element that matches what the control does.

  • A link (a with href) takes the user somewhere: another page, another part of the page, a file, or a mail address. Users expect to be able to open it in a new tab, copy the address and bookmark it.
  • A button does something on the current page: submit a form, open a menu, play a video, delete an item. It has no address.

Using the right element gives you behaviour for free. A link is focusable, works with Enter, and shows its address on hover. A button is focusable and works with both Enter and Space. A div with a click handler has none of this. It cannot be reached with the Tab key and is not announced as a control by screen readers, so it needs a role, a tabindex and key handlers to match, and it is better not to build it at all.

Details that matter. An a without href is not focusable and is not a link. A button inside a form submits it by default, because its default type is submit. Write type="button" for buttons that should not submit. You can style a link to look like a button, or a button to look like a link. The element still decides the meaning.

The first button has no type, so it is a submit button. The second is a plain button and does not submit. The a without href cannot receive focus, while the one with href can. The last link looks like a button but still navigates, which is correct because it goes to a new page.

A quick test: if it changes the address, use a link. If it changes something on the current page, use a button.

html
<form id="f" action="/enrol" method="post">
  <input name="email" type="email" required>
  <button id="send">Send</button>
  <button id="menu" type="button" aria-expanded="false">Menu</button>
</form>
<a id="real" href="/courses">See all courses</a>
<a id="fake">Not a link</a>
<style>
  .btn { display: inline-block; padding: 0.5rem 1rem; background: #0a6cff; color: #fff; text-decoration: none; border-radius: 4px; }
</style>
<a class="btn" id="cta" href="/signup">Create account</a>

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

  • Links navigate; buttons perform actions.
  • a without href is not focusable and not a link.
  • A button in a form defaults to type submit.
  • Native elements provide keyboard support and roles.
  • Style does not change meaning: a link can look like a button.

Common mistakes

  • Using a div or span with an onclick for something that should be a button.
  • Using a link with href="#" and a click handler to run an action. Use a button for actions.
  • Forgetting that a button in a form submits by default, and then getting a page reload when it should only open a menu.

Follow-ups

  • What is the default type of a button inside a form?
  • How would you make an existing div clickable if you cannot change the markup, and why is it a poor choice?

Tips

  • Use the address test: does it change the URL? Link. Does it act on this page? Button.
  • Mention that a link styled as a button is fine, as long as it navigates.
63.html-css-0063Easyfresher

Why does a page need a charset declaration, and what are HTML entities for?

The charset declaration tells the browser which encoding maps stored numbers to characters, and UTF-8 is the standard. Entities such as &lt; and &amp; write characters that HTML reserves, and escaping user text prevents it from being treated as markup.

Full answer

Text in a file is stored as numbers. The character encoding is the table that maps those numbers to letters. If the browser guesses the wrong table, text such as the rupee sign or the euro sign turns into strange symbols. Declare the encoding with <meta charset="utf-8"> near the top of the head, and save the file as UTF-8. UTF-8 covers every language and is the standard choice.

Some characters have a special meaning in HTML. The < character starts a tag and & starts an entity. To show them as plain text, write an entity.

  • &lt; for <
  • &gt; for >
  • &amp; for &
  • &quot; for a double quote inside an attribute value
  • &nbsp; for a non-breaking space, which stops a line from breaking between two words
  • &copy; for the copyright sign

You can also write a character by its number: &#8364; or &#x20AC; for the euro sign. With UTF-8 you can type most characters directly, so numeric entities are only needed for the few reserved characters and for characters that are hard to type.

Entities matter for safety too. When user text is put into a page, it must be escaped, or text like <script> would run as code. Setting textContent in JavaScript treats the value as plain text, while innerHTML treats it as markup.

The first paragraph shows a euro sign and a rupee sign. The second shows the tags as visible text. The third keeps "Mr." and "Sharma" on one line. The last prints the tag characters literally, because textContent does not parse markup.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Entities</title>
</head>
<body>
  <p id="a">Price: &#8364;20 or &#x20B9;1,700</p>
  <p id="b">Write &lt;h1&gt; for a heading &amp; &lt;p&gt; for a paragraph.</p>
  <p id="c">Mr.&nbsp;Sharma</p>
  <p id="d"></p>
  <script>
    document.getElementById("d").textContent = "<b>not bold</b>";
  </script>
</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

  • <meta charset="utf-8"> belongs early in the head and must match how the file is saved.
  • UTF-8 covers all languages.
  • Entities like &lt;, &gt; and &amp; show reserved characters as text.
  • &nbsp; prevents a line break between two words.
  • Escape or use textContent for user text to avoid injection.

Common mistakes

  • Forgetting the charset declaration and seeing broken characters when the server does not send an encoding.
  • Saving the file in an old encoding while the page declares UTF-8, which produces the same broken characters.
  • Putting user input into innerHTML without escaping it, which allows script injection.

Follow-ups

  • What happens if the charset is declared late in the head?
  • What is the difference between textContent and innerHTML when inserting user text?

Tips

  • State the pair that must match: the file is saved as UTF-8 and the page says utf-8.
  • Name the five or six common entities and when &nbsp; is useful.
64.html-css-0064Easyfresher

How do CSS shorthand properties such as margin, padding and background work, and what can go wrong with them?

Shorthands set several properties together: margin and padding take one to four values in the order top, right, bottom, left. Any longhand not mentioned in a shorthand is reset to its initial value, so later shorthands can silently undo earlier rules.

Full answer

A shorthand sets several related properties in one line. The most used are margin, padding, border, background, font, flex and inset.

For margin and padding, the number of values decides the sides.

  • One value: all four sides.
  • Two values: top and bottom, then left and right.
  • Three values: top, then left and right, then bottom.
  • Four values: top, right, bottom, left, clockwise from the top. A memory aid is "TRouBLe".

Related shorthands such as margin-inline: 1rem set the left and right sides (in left-to-right text), and margin-block sets the top and bottom.

A shorthand always sets every longer property it covers. Any value you leave out is reset to its initial value. This is the usual cause of surprises. If you write background-size: 50% and later background: red, the shorthand resets background-size to auto. The font shorthand also resets line-height, so font: 16px Georgia after a custom line-height removes it.

Box D has 10px at the top, 20px on the right, 30px at the bottom and 40px on the left. Box E has rounded corners on the top-left and bottom-right only. In the reset paragraph the font shorthand wipes out the earlier line-height, so the line height returns to normal, while in the keep paragraph the longhand comes after and wins. The background shorthand resets the earlier background-size.

When you want to change one part only, use the longhand, such as background-color, so you do not reset the others.

html
<style>
  .a { padding: 10px; }
  .b { padding: 10px 20px; }
  .c { padding: 10px 20px 30px; }
  .d { padding: 10px 20px 30px 40px; }
  .e { border: 2px solid teal; border-radius: 8px 0 8px 0; }
  .reset { line-height: 40px; font: 16px Georgia; }
  .keep  { font: 16px Georgia; line-height: 40px; }
  .bg    { background-size: 50%; background: red; }
</style>
<div class="a" id="a">A</div>
<div class="b" id="b">B</div>
<div class="c" id="c">C</div>
<div class="d" id="d">D</div>
<div class="e" id="e">E</div>
<p class="reset" id="reset">Font after line-height</p>
<p class="keep" id="keep">Line-height after font</p>
<div class="bg" id="bg">Background</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

  • margin and padding take 1 to 4 values: top, right, bottom, left.
  • Two values mean vertical then horizontal.
  • A shorthand resets every longhand it covers that you leave out.
  • font resets line-height; background resets size and position.
  • Use a longhand to change one part only.

Common mistakes

  • Writing margin: 10px 20px and thinking the values are left and right then top and bottom. The first is vertical, the second is horizontal.
  • Using the background shorthand after background-size and losing the size.
  • Putting the font shorthand after line-height and losing the line height.

Follow-ups

  • What does margin: 0 auto do?
  • How would you change only the background color without resetting the other background properties?

Tips

  • Say the clockwise order out loud when you answer: top, right, bottom, left.
  • Mention the reset behaviour. It is the detail that shows you have debugged shorthand problems.
65.html-css-0065Easyfresher

How do border, border-radius, box-shadow and outline differ, and how do you make a circle or a pill shape?

border is part of the box and changes its size, border-radius rounds corners (50% gives a circle on a square, a large value gives a pill), box-shadow and outline are drawn without taking space. Outline is the property to use for focus rings.

Full answer

These four properties draw lines and shapes around a box, but they behave differently.

  • border is part of the box. It takes space and changes the size of the element (unless box-sizing: border-box absorbs it into the width).
  • border-radius rounds the corners of the box and its background. A value of 50% on a square makes a circle. A very large value such as 999px on a rectangle makes a pill shape with fully round ends.
  • box-shadow draws a shadow outside the border (or inside with inset). The syntax is offset-x offset-y blur spread color. It takes no space and does not push other elements. You can list several shadows separated by commas.
  • outline is drawn outside the border and takes no space. In current browsers it follows the rounded corners of border-radius. It is the property used for focus rings, and outline-offset moves it away from the box.

Because shadows and outlines do not affect layout, they are good for hover and focus effects. Changing border-width on hover makes the content jump, so use a shadow or outline instead.

The first box is a circle and the pill has round ends. The bordered box is 92px wide, because the 6px border adds 12px to the width of 80px. The outlined box stays 80px wide, since the outline takes no room. The inset shadow draws a teal ring inside the box without changing its size.

For a focus ring, prefer outline with outline-offset, and never remove it without giving something equally visible back.

html
<style>
  body { margin: 0; padding: 20px; font-family: sans-serif; }
  .box { width: 80px; height: 80px; background: #cde; margin-bottom: 16px; }
  .circle { border-radius: 50%; }
  .pill { width: 160px; height: 40px; border-radius: 999px; background: #0a6cff; color: #fff; text-align: center; line-height: 40px; }
  .card { box-shadow: 0 2px 6px rgba(0, 0, 0, 0.25), 0 0 0 1px #ccc; }
  .bordered { border: 6px solid #333; }
  .outlined { outline: 6px solid #333; outline-offset: 2px; }
  .inset { box-shadow: inset 0 0 0 4px teal; }
</style>
<div class="box circle" id="circle"></div>
<div class="pill" id="pill">Enrol now</div>
<div class="box card" id="card"></div>
<div class="box bordered" id="bordered"></div>
<div class="box outlined" id="outlined"></div>
<div class="box inset" id="inset"></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 takes space; box-shadow and outline do not.
  • border-radius: 50% on a square gives a circle; a large value gives a pill.
  • box-shadow syntax: offset-x offset-y blur spread color, with optional inset.
  • outline is for focus rings and can be moved with outline-offset.
  • Prefer shadow or outline for hover effects so layout does not jump.

Common mistakes

  • Increasing border-width on hover and making the content jump. Use outline or box-shadow for effects.
  • Removing the outline from buttons and links without a replacement focus style.
  • Using border-radius: 50% on a rectangle and getting an oval instead of a pill. Use a large pixel value for a pill.

Follow-ups

  • What do the four numbers in box-shadow mean?
  • How would you draw a focus ring that does not move the layout?

Tips

  • Remember the one-line rule: border takes space, shadow and outline do not.
  • Explain a card shadow in two layers, a soft blur and a thin ring, to show practical use.
66.html-css-0066Easyfresher

How do background-size, background-position and multiple backgrounds work, and how do you put text on an image safely?

background-image takes urls and gradients, background-size scales them (cover fills and crops, contain fits), position places them and repeat controls tiling. Several backgrounds can be listed, with the first on top, which makes a gradient overlay on a photo easy.

Full answer

A CSS background paints behind the content of a box. The image comes from background-image, which accepts a url() or a gradient such as linear-gradient().

The main controls are:

  • background-size: auto (natural size), a length or percentage, cover (scale until the box is covered, cropping if needed) or contain (scale until the whole image fits, leaving gaps).
  • background-position: where the image sits, such as center, top left or 20% 80%.
  • background-repeat: repeat is the default. Use no-repeat for a single image.
  • background-attachment: scroll by default. fixed keeps the image still while the page scrolls, but it can behave differently on touch devices, so test it.

You can give several backgrounds at once, separated by commas. The first one is on top. A common use is a dark gradient over a photo, so white text stays readable. The gradient goes first, because it is the top layer.

Use a background for decoration. If the picture carries meaning, use an img with alt, because backgrounds are invisible to screen readers.

The hero has two background layers: a 55 percent black gradient on top and the picture below, so the heading stays readable whatever the picture looks like. cover scales the picture to fill the box. The second box is a pattern made only from a gradient, with no image file at all.

For photos that carry content, such as a product picture, use img and object-fit so the image stays in the accessibility tree.

html
<style>
  .hero {
    min-height: 160px;
    padding: 24px;
    color: #fff;
    background:
      linear-gradient(rgba(0, 0, 0, 0.55), rgba(0, 0, 0, 0.55)),
      url("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");
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
  }
  .stripes {
    height: 40px;
    background: repeating-linear-gradient(45deg, #0a6cff 0 10px, #ffffff 10px 20px);
  }
</style>
<div class="hero" id="hero"><h1>Admissions open</h1></div>
<div class="stripes" id="stripes"></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

  • background-image accepts url() and gradients.
  • cover fills the box and crops; contain fits the whole image.
  • Multiple backgrounds are comma-separated; the first is on top.
  • A dark gradient over a photo keeps text readable.
  • Backgrounds are decorative; use img with alt for meaningful pictures.

Common mistakes

  • Using a background image for content that needs alt text, so screen reader users miss it.
  • Putting the gradient after the image in the list, so the image covers it and the overlay never shows.
  • Relying on background-attachment: fixed for a parallax effect without testing on phones, where it can behave differently.

Follow-ups

  • What is the difference between background-size: cover and contain?
  • How would you add a second background image behind the first?

Tips

  • State which layer is on top: the first one in the list.
  • Mention the gradient overlay trick for text on photos. It is a very common design need.
67.html-css-0067Easyfresher

What do the overflow values visible, hidden, scroll, auto and clip do?

overflow controls what happens to content bigger than its box: visible spills out, hidden cuts it, scroll always shows scrollbars, auto shows them when needed, and clip cuts it without making the box scrollable. If one axis is not visible, the other visible axis becomes auto.

Full answer

Overflow happens when content is bigger than its box. The overflow property says what to do with the extra part.

  • visible: the default. The extra content spills outside the box and is drawn there.
  • hidden: the extra content is cut off. The box can still be scrolled by code, for example with scrollTop, but the user gets no scrollbar.
  • scroll: the box always shows scrollbars, even when nothing overflows.
  • auto: scrollbars appear only when content overflows. This is usually the best choice for scrolling areas.
  • clip: the extra content is cut off like hidden, but the box is not a scroll container and cannot be scrolled at all, even by code.

A box needs a limited size, for example a height or max-height, for vertical overflow to happen. Without it, the box simply grows.

overflow-x and overflow-y can be set separately, with a twist. If one is visible and the other is not, visible is treated as auto. So overflow-x: hidden alone also makes the vertical direction scrollable when content overflows. A box with any overflow value other than visible or clip also becomes a new block formatting context, and it becomes the scroll container that position: sticky looks at.

Each box shows 60px of a 200px tall child. The visible box lets the child spill over the boxes below. The auto box adds a vertical scrollbar. The xonly box was given only overflow-x: hidden, yet its computed overflow-y is auto. The clip box cannot be scrolled even by a script.

Think before adding overflow: hidden to fix a layout problem. It can cut off shadows and focus rings, and it can break sticky positioning for children.

html
<style>
  .box { width: 120px; height: 60px; border: 1px solid #333; margin-bottom: 8px; font: 14px/20px sans-serif; }
  .tall { height: 200px; background: #eef; }
  #hidden { overflow: hidden; }
  #scroll { overflow: scroll; }
  #auto   { overflow: auto; }
  #clip   { overflow: clip; }
  #xonly  { overflow-x: hidden; }
</style>
<div class="box" id="visible"><div class="tall"></div></div>
<div class="box" id="hidden"><div class="tall"></div></div>
<div class="box" id="scroll"><div class="tall"></div></div>
<div class="box" id="auto"><div class="tall"></div></div>
<div class="box" id="clip"><div class="tall"></div></div>
<div class="box" id="xonly"><div class="tall"></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

  • visible is the default and lets content spill out.
  • hidden cuts off the content; scroll and auto add scrollbars.
  • clip cuts content but the box cannot be scrolled at all.
  • A visible axis becomes auto when the other axis is not visible.
  • Non-visible overflow creates a scroll container, which affects sticky positioning.

Common mistakes

  • Adding overflow: hidden to hide a horizontal scrollbar and cutting off dropdown menus or focus rings.
  • Expecting overflow-x: hidden alone to leave overflow-y visible. The computed value becomes auto.
  • Using overflow: scroll everywhere. It shows empty scrollbars on systems with always-visible scrollbars. Use auto.

Follow-ups

  • Why does overflow: hidden on a parent break position: sticky on its child?
  • What is the difference between hidden and clip?

Tips

  • Say that auto is the normal choice for scroll areas, and explain clip as the version that cannot scroll.
  • Mention sticky when talking about overflow. It is the common side effect interviewers ask about.
68.html-css-0068Easyfresher

How do you build an accordion with details and summary, and what do you get for free?

details and summary form a built-in disclosure widget with keyboard support, an open attribute, a toggle event and correct announcements. Elements sharing a name attribute can behave as an exclusive accordion in browsers that support it.

Full answer

The details element is a built-in show and hide widget. Its first child summary is the always-visible label. Everything else inside details is shown only when the widget is open. Clicking the summary, or pressing Enter or Space when it has focus, toggles it.

What you get with no JavaScript:

  • It is reachable with the keyboard, and screen readers announce it as expandable with its open or closed state.
  • The open attribute shows whether it is open. Add open in the HTML to start expanded.
  • A toggle event fires on change, so scripts can react.

To make an exclusive accordion where opening one item closes the others, give the details elements the same name attribute. This is newer, so check the support table. Without it, you need a small script.

You can style the marker with summary::marker, or hide it with list-style: none on summary and add your own icon. Animating the open and close needs extra work, because the content jumps between display states.

The first item starts open. Because both share name="faq", opening the second closes the first and fires the toggle event, which updates the log line.

Use details for FAQs and simple disclosures. For navigation menus with complex behaviour, such as arrow-key movement, you still need script and ARIA.

html
<style>
  details { border: 1px solid #999; border-radius: 6px; padding: 0.5rem 1rem; margin-bottom: 0.5rem; }
  summary { cursor: pointer; font-weight: bold; }
  summary:focus-visible { outline: 3px solid #0a6cff; outline-offset: 2px; }
  details[open] summary { margin-bottom: 0.5rem; }
</style>
<details name="faq" id="q1" open>
  <summary>How long is the course?</summary>
  <p>Twelve weeks, with two live sessions each week.</p>
</details>
<details name="faq" id="q2">
  <summary>Do I get a certificate?</summary>
  <p>Yes, after you finish the final project.</p>
</details>
<p id="log"></p>
<script>
  document.getElementById("q2").addEventListener("toggle", e => {
    document.getElementById("log").textContent = "q2 open: " + e.target.open;
  });
</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

  • summary is the visible label; the rest of details is the hidden content.
  • The open attribute shows and sets state; the toggle event reports changes.
  • Keyboard and screen reader support are built in.
  • Elements with the same name form an exclusive group, where supported.
  • Style the marker with summary::marker or replace it with your own icon.

Common mistakes

  • Putting something other than summary as the first child. The browser then adds a default label, such as Details.
  • Removing the summary focus outline and leaving keyboard users without a visible focus state.
  • Rebuilding the widget with divs and scripts when details already provides the behaviour and accessibility.

Follow-ups

  • How do you make only one details open at a time?
  • How do you detect when a details element is opened by script?

Tips

  • Mention what you do not need to write: no script, no ARIA state, no key handling.
  • Say that the name attribute for exclusive groups is newer and check support before depending on it.
69.html-css-0069Hardsenior

How does the iframe sandbox attribute work, and how do you embed third-party content safely?

The sandbox attribute puts an iframe under strict restrictions and an opaque origin, and tokens such as allow-scripts and allow-forms give back specific powers. Combining allow-scripts with allow-same-origin on same-origin content defeats the sandbox. Embedded sites can also block framing with headers.

Full answer

An iframe embeds another page inside yours. The embedded page can run scripts, submit forms, open popups and, if it comes from your own origin, read and change your page. When the content is untrusted, such as user-submitted HTML, a payment widget or an ad, restrict it.

The sandbox attribute switches on a strict set of restrictions. With sandbox and no value, the frame cannot run scripts, submit forms, open popups, use plugins, or change the address of the top page, and its content is treated as coming from a unique opaque origin. You then give back only the powers needed using tokens:

  • allow-scripts lets scripts run.
  • allow-forms lets forms submit.
  • allow-popups lets it open new windows.
  • allow-same-origin lets it keep its real origin instead of the opaque one.

Be careful with the last two together. If the embedded content comes from the same origin as your page and you give both allow-scripts and allow-same-origin, the frame's script can remove its own sandbox attribute, so the sandbox protects nothing. Use that pair only for content from a different origin.

Other attributes: title names the frame for screen readers, loading="lazy" delays loading, referrerpolicy limits what address is sent, and allow grants permissions such as the camera or fullscreen to specific frames.

The embedded site can also refuse framing. A site sends the X-Frame-Options header or a Content-Security-Policy: frame-ancestors rule to say which pages may embed it. If a page will not show up in your frame, check those headers first.

Both frames contain a script that tries to read the parent page. The first frame, without sandbox, shares the origin of the page, so the read works and it reports allowed. The second frame has sandbox="allow-scripts", so it runs scripts but has an opaque origin, and the browser blocks the read. It reports blocked.

Treat the sandbox as one layer. Pair it with a Content Security Policy and with server-side checks on anything the frame sends back.

html
<pre id="out">waiting</pre>
<iframe id="open" title="Not sandboxed" width="200" height="40"
  srcdoc="<script>try { parent.document.title; parent.postMessage('a:allowed', '*'); } catch (e) { parent.postMessage('a:blocked', '*'); }</script>"></iframe>
<iframe id="boxed" title="Sandboxed" width="200" height="40" sandbox="allow-scripts"
  srcdoc="<script>try { parent.document.title; parent.postMessage('b:allowed', '*'); } catch (e) { parent.postMessage('b:blocked', '*'); }</script>"></iframe>
<script>
  window.results = {};
  window.addEventListener("message", e => {
    const [who, what] = String(e.data).split(":");
    results[who] = what;
    document.getElementById("out").textContent = JSON.stringify(results);
  });
</script>

The framed pages are inline srcdoc pages, not real third-party sites. The check confirmed that the plain frame could read the parent page and the sandboxed frame could not. 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

  • sandbox with no value blocks scripts, forms, popups and gives an opaque origin.
  • Tokens such as allow-scripts and allow-forms restore specific abilities.
  • allow-scripts plus allow-same-origin on same-origin content removes the protection.
  • title, loading and referrerpolicy are good defaults for every iframe.
  • X-Frame-Options and CSP frame-ancestors decide whether a site can be framed.

Common mistakes

  • Using allow-scripts together with allow-same-origin on same-origin content. The frame can then remove its own sandbox.
  • Leaving out the title attribute, so screen reader users hear only that there is a frame.
  • Assuming any site can be embedded. Many send X-Frame-Options or frame-ancestors headers that block it.

Follow-ups

  • What does an empty sandbox attribute block?
  • Why does the same-origin iframe in the example read the parent while the sandboxed one cannot?

Tips

  • Start from the principle: begin with a full sandbox and add only the tokens you need.
  • Mention the framing headers on the embedded side. It explains the most common 'blank iframe' bug.
70.html-css-0070Mediummid

How do :target and :checked let you build interactive effects without JavaScript, and when should you not?

:target matches the element whose id is in the page address fragment, and :checked matches checked inputs, so CSS can react to them with no script. They are useful for highlighting and custom form controls, but menus and dialogs built from them have accessibility and history problems.

Full answer

Some CSS selectors match state that the browser already tracks, so CSS can react without scripts.

:target matches the element whose id equals the fragment in the page address. When the address ends in #faq, the element with id="faq" matches :target. It is handy for highlighting the section a link points to, or for simple in-page tabs.

:checked matches a checked checkbox or radio button, and a selected option. With the sibling combinators + and ~, a hidden checkbox can toggle styles on later elements. This is called the checkbox hack. :has() allows the reverse, such as styling a parent when its checkbox is checked.

Both techniques have costs.

  • :target changes the address and adds a history entry, and the browser scrolls to the element. That may be unwanted for a menu or a popup.
  • A checkbox used as a toggle is read by screen readers as a checkbox, not as a menu button, and it has no aria-expanded state.
  • Content that appears in CSS only is easy to build and hard to make fully accessible.

For real menus, dialogs and accordions, prefer details, dialog or a button with a small script. Use :target for highlighting and :checked for form controls styled by the state they already have.

After clicking the Fees link, the address ends in #fees and that section gets a blue left border and a light background. The radio inputs are visually hidden but still focusable. The label next to the checked one turns blue, and a keyboard user sees an outline on the label when its input has focus.

Note that the hidden input uses opacity: 0 and not display: none. With display: none the control would leave the keyboard order.

html
<style>
  section { padding: 8px; border-left: 4px solid transparent; }
  section:target { border-left-color: #0a6cff; background: #eef4ff; }
  .opt input { position: absolute; opacity: 0; }
  .opt label { display: inline-block; padding: 4px 12px; border: 1px solid #999; cursor: pointer; }
  .opt input:checked + label { background: #0a6cff; color: #fff; }
  .opt input:focus-visible + label { outline: 3px solid #0a6cff; outline-offset: 2px; }
</style>
<nav><a href="#fees" id="l1">Fees</a> <a href="#dates" id="l2">Dates</a></nav>
<section id="fees">Fees information</section>
<section id="dates">Dates information</section>
<div class="opt">
  <input type="radio" name="plan" id="p1" checked><label for="p1" id="lab1">Monthly</label>
  <input type="radio" name="plan" id="p2"><label for="p2" id="lab2">Yearly</label>
</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

  • :target matches the element named by the URL fragment.
  • :checked with + or ~ lets a control style later elements.
  • Visually hide inputs but keep them focusable.
  • :target changes history and scrolls the page.
  • Prefer details, dialog or a button for menus and popups.

Common mistakes

  • Hiding the radio or checkbox with display: none, which removes it from keyboard focus.
  • Building menus that open with :target, which scroll the page and fill the history with entries.
  • Using a checkbox as a menu toggle without any accessible name or state for screen reader users.

Follow-ups

  • Why use opacity: 0 instead of display: none on the hidden input?
  • What does :has() add to the checkbox hack?

Tips

  • Say what each selector reads: :target reads the fragment, :checked reads a control's state.
  • Give one good use for each, and one case where you would use a different tool.
71.html-css-0071Mediummid

How do you prepare a page for printing with @media print and page-break rules?

A print stylesheet uses @media print to hide navigation and controls, set dark text on white, show link addresses with attr(href), and control page breaks with break-inside, break-after and @page. Test with print media emulation and the print preview.

Full answer

People still print or save as PDF: certificates, fee receipts, timetables and articles. A print stylesheet changes the page for paper without touching the screen version. Write it with @media print { ... }, or a separate file loaded with media="print".

Common jobs:

  • Hide things that make no sense on paper: navigation, buttons, video, ads, cookie banners.
  • Use dark text on a white background and drop large background images. Browsers often skip backgrounds by default to save ink.
  • Show where links go: a[href]::after { content: " (" attr(href) ")"; }. Skip it for fragment links and javascript: links.
  • Control page breaks: break-inside: avoid keeps a card or table row together, break-after: page forces a new page, and break-after: avoid on headings keeps a heading with the text after it.
  • Set page size and margins with @page { margin: 2cm; }.
  • Units from the paper world, such as pt, cm and in, make sense in print. Layouts based on vw do not.

You can test without printing. DevTools has a print media emulation option, and the checks for this example emulate the media type.

On screen the navigation and the Print button are visible. When the page is printed, they disappear, the link shows its full address after the text, each receipt stays on one page, and the heading stays with the content that follows.

Always preview with the browser's print dialog, because margins, headers and footers differ between browsers.

html
<style>
  body { font: 16px/1.5 Georgia, serif; }
  nav, .no-print { display: block; background: #eee; padding: 8px; }
  .receipt { border: 1px solid #333; padding: 8px; margin-bottom: 8px; }
  @page { margin: 2cm; }
  @media print {
    nav, .no-print { display: none; }
    body { color: #000; background: #fff; font-size: 12pt; }
    a[href^="http"]::after { content: " (" attr(href) ")"; font-size: 10pt; }
    .receipt { break-inside: avoid; }
    h2 { break-after: avoid; }
  }
</style>
<nav id="nav">Home | Fees | Contact</nav>
<h2 id="h2">Fee receipts</h2>
<div class="receipt" id="r1">Receipt 1001 for Asha</div>
<p>Read the <a id="link" href="https://example.com/policy">refund policy</a>.</p>
<button class="no-print" id="btn" type="button">Print</button>

The check used print media emulation in Chrome, not a real printer or print preview, so margins, headers and footers were not checked. 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

  • @media print applies only when printing or saving as PDF.
  • Hide navigation, buttons and ads for paper.
  • a[href]::after with attr(href) prints link addresses.
  • break-inside, break-after and @page control pagination.
  • Do not depend on background colors for meaning in print.

Common mistakes

  • Printing the page with the sticky header and fixed elements that repeat or cover content on every page.
  • Forgetting break-inside: avoid, so a table row or card is split across two pages.
  • Showing href for every link, including # links and javascript: links, which print as noise.

Follow-ups

  • How do you force a new page before each chapter?
  • How can you show a link's address next to its text in print?

Tips

  • Mention emulating print media in DevTools. It proves you test the result.
  • Say that backgrounds are often not printed by default, so important information must not depend on them.
72.html-css-0072Mediummid

How do you build a swipeable carousel with CSS scroll snap, and what accessibility points matter?

Scroll snap uses scroll-snap-type on the scroll container and scroll-snap-align on children to stop at defined positions. Make the scroller focusable and named, add buttons or links for non-touch users, and avoid auto-advance.

Full answer

Scroll snap makes a scrolling box stop at chosen positions, which gives the feel of a slideshow with no JavaScript.

Two sides work together.

  • On the scroll container: overflow-x: auto (or scroll) and scroll-snap-type: x mandatory. The first word is the axis. mandatory always snaps to a point, while proximity snaps only when the scroll ends near one.
  • On each child: scroll-snap-align: start, center or end marks where the child should align. scroll-snap-stop: always stops fast swipes from skipping over several items.

scroll-padding on the container leaves room for things like a sticky header. scroll-margin on children does the same per item. Flex with flex: 0 0 100% makes each slide as wide as the container.

Accessibility needs care. The scroll area should be reachable and named. Add tabindex="0", a role="region" and an aria-label so keyboard users can focus it and use the arrow keys, because not every browser makes scrollable areas focusable by default. Do not hide the content that is off-screen. Provide visible previous and next buttons or links for people who cannot swipe. Avoid auto-advancing slides.

Each slide fills the 300px track. If you scroll the track to 200px and let go, it snaps to 300px, the start of slide 2. The numbered links give a non-swipe way to reach each slide, and the track can be focused and scrolled with the arrow keys.

Test with a mouse wheel, a touch screen and a keyboard. Behaviour at the edges differs a little between browsers.

html
<style>
  body { margin: 0; font-family: sans-serif; }
  .track {
    display: flex;
    width: 300px;
    overflow-x: auto;
    scroll-snap-type: x mandatory;
  }
  .slide {
    flex: 0 0 100%;
    height: 120px;
    scroll-snap-align: start;
    scroll-snap-stop: always;
    display: grid; place-items: center;
    font-size: 24px;
  }
  .slide:nth-child(1) { background: #cde; }
  .slide:nth-child(2) { background: #fcd; }
  .slide:nth-child(3) { background: #dfc; }
</style>
<div class="track" id="track" tabindex="0" role="region" aria-label="Course highlights">
  <div class="slide" id="s1">Slide 1</div>
  <div class="slide" id="s2">Slide 2</div>
  <div class="slide" id="s3">Slide 3</div>
</div>
<p><a href="#s1">1</a> <a href="#s2">2</a> <a href="#s3">3</a></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

  • scroll-snap-type sets the axis and strictness on the container.
  • scroll-snap-align on children marks the snap points.
  • scroll-padding and scroll-margin offset the snap positions.
  • Add tabindex, a label and visible controls for accessibility.
  • Do not auto-advance slides without a pause control.

Common mistakes

  • Using mandatory snapping with slides taller than the container, which can trap users away from content.
  • Building a carousel that only works by swiping, with no buttons or links.
  • Auto-advancing slides with no pause control, which fails accessibility guidelines for moving content.

Follow-ups

  • What is the difference between mandatory and proximity?
  • How would you keep the snapped item from hiding behind a sticky header?

Tips

  • Explain the two sides: type on the container and align on the children.
  • Mention proximity as the gentler option for long content.
73.html-css-0073Mediummid

A fixed header covers the target when you click an in-page link. How do you fix it and add smooth scrolling?

scroll-padding-top on the scroll container, or scroll-margin-top on targets, leaves room for a fixed header when jumping to anchors. scroll-behavior: smooth animates the jump and should be limited to users without a reduced motion preference.

Full answer

When a link points to #section, the browser scrolls so the top of that element touches the top of the viewport. A fixed or sticky header sits on top of that spot and hides the first lines of the target.

There are two simple fixes, and both use scroll offsets that the browser takes into account.

  • scroll-margin-top on the targets leaves space above each one. It is part of the element, so it works even if the header height differs per page.
  • scroll-padding-top on the scrolling container (usually html) applies to every target in it. This is the shortest solution when one header covers the whole site.

Smooth scrolling is scroll-behavior: smooth on the scroll container. It animates anchor jumps and scrollIntoView calls. Some users get dizzy from large animated movement, so wrap it in a check for the reduced motion preference: use smooth scrolling only when prefers-reduced-motion: no-preference.

Clicking the Fees link scrolls so that the section starts 64px below the top, exactly under the header, because of scroll-padding-top. The Notes section has its own scroll-margin-top: 100px, which adds a larger gap for that one target. Both are applied while the page scrolls smoothly if the user has no reduced motion preference.

Do not use scroll-behavior: smooth on very long pages without thinking. A jump across many screens takes a long time and can feel slow.

html
<style>
  html { scroll-padding-top: 64px; }
  @media (prefers-reduced-motion: no-preference) {
    html { scroll-behavior: smooth; }
  }
  body { margin: 0; font-family: sans-serif; }
  header { position: fixed; inset: 0 0 auto 0; height: 64px; background: #333; color: #fff; padding: 0 16px; display: flex; align-items: center; gap: 16px; }
  header a { color: #fff; }
  section { height: 700px; padding-top: 80px; }
  #notes { scroll-margin-top: 100px; }
</style>
<header id="hdr"><a href="#fees" id="l1">Fees</a><a href="#notes" id="l2">Notes</a></header>
<section id="intro">Intro</section>
<section id="fees">Fees</section>
<section id="notes">Notes</section>

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 jumps align the target's top with the viewport top.
  • scroll-margin-top on a target and scroll-padding-top on the scroller add an offset.
  • scroll-behavior: smooth animates anchor jumps and scrollIntoView.
  • Wrap smooth scrolling in prefers-reduced-motion: no-preference.
  • Use a custom property for the header height.

Common mistakes

  • Adding padding-top to the body to hide the header problem. It does nothing for scroll targets.
  • Applying smooth scrolling for everyone, including users who asked for reduced motion.
  • Hard-coding the header height in many places instead of using one custom property.

Follow-ups

  • What is the difference between scroll-margin and scroll-padding?
  • How does JavaScript scrollIntoView use smooth scrolling?

Tips

  • Say that scroll-padding goes on the scroller and scroll-margin goes on the target.
  • Keep the header height in a custom property and use it for both the header and the scroll offset.
74.html-css-0074Mediummid

What do filter, backdrop-filter and mix-blend-mode do, and what side effects do they have?

filter changes how an element and its contents are drawn, backdrop-filter changes what is seen behind a translucent element, and mix-blend-mode blends with the content underneath. They create stacking contexts, filter also becomes a containing block for fixed descendants, and large blurs are costly.

Full answer

These three properties change how pixels are drawn.

filter applies effects to the element itself and everything inside it: blur(), grayscale(), brightness(), contrast(), drop-shadow() and others, often chained. drop-shadow() follows the shape of the drawn pixels, so it works on a transparent PNG or an SVG shape, while box-shadow always shadows the rectangle.

backdrop-filter applies the effect to whatever is behind the element, seen through its semi-transparent background. The "frosted glass" look is backdrop-filter: blur(8px) plus a translucent background colour. It needs the element's own background to be at least partly transparent, or nothing shows.

mix-blend-mode blends the element's colours with what is behind it, with modes such as multiply, screen and overlay. A common use is multiply for a logo that should look printed on a coloured photo.

Side effects to remember:

  • A filter (other than none), backdrop-filter or mix-blend-mode creates a stacking context.
  • A filter also makes the element the containing block for fixed and absolute descendants. A position: fixed child of a filtered parent is positioned against that parent, not the viewport.
  • Large blurs are costly to draw, especially on phones and when animated. Test performance on real devices.

The glass panel blurs the gradient behind it. The image is shown in grey. The red square has position: fixed; top: 0; left: 0, yet it is drawn at the top-left corner of its filtered parent, which sits well below the top of the window, and not at the top of the window. That is the containing block effect.

Use filter for effects and opacity for plain fading, and keep an eye on contrast, because blur and blend modes can lower text legibility.

html
<style>
  body { margin: 0; font-family: sans-serif; }
  .photo { position: relative; height: 120px; background: linear-gradient(90deg, #f66, #6af); }
  .glass { position: absolute; inset: 20px; padding: 12px; background: rgba(255, 255, 255, 0.35); backdrop-filter: blur(6px); }
  .gray { filter: grayscale(100%); }
  .multiply { mix-blend-mode: multiply; background: #ccc; padding: 8px; }
  .wrap { margin-top: 100px; filter: blur(0px); }
  .fixed-child { position: fixed; top: 0; left: 0; width: 40px; height: 40px; background: tomato; }
</style>
<div class="photo" id="photo"><div class="glass" id="glass">Frosted panel</div></div>
<img class="gray" id="img" alt="Campus" width="80" height="40" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='80' height='40'%3E%3Crect width='80' height='40' fill='%23f66'/%3E%3C/svg%3E">
<div class="multiply" id="mul">Multiply</div>
<div class="wrap" id="wrap"><div class="fixed-child" 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

  • filter applies to the element and its children; backdrop-filter to what is behind it.
  • drop-shadow follows drawn shapes; box-shadow follows the box.
  • mix-blend-mode blends with the colors behind, for example multiply.
  • filter and backdrop-filter create a stacking context; filter also contains fixed descendants.
  • Large or animated blurs can be slow.

Common mistakes

  • Applying filter to a parent of a fixed element and wondering why the fixed element no longer sticks to the viewport.
  • Using backdrop-filter with an opaque background, so there is nothing to see through.
  • Animating large blur values on many elements, which makes scrolling and animation slow.

Follow-ups

  • What is the difference between filter: drop-shadow() and box-shadow?
  • Why does a fixed child move with its filtered parent?

Tips

  • Say that drop-shadow follows the shape of the pixels and box-shadow follows the box.
  • Name the stacking context and containing block side effects. They are the real-world bugs.
75.html-css-0075Mediummid

How do clip-path and mask-image shape an element, and how do they affect clicks?

clip-path cuts an element to a shape such as a circle or polygon with sharp edges, and mask-image shows or hides parts using an image or gradient, so it can fade. Clipped areas are not clickable, and shadows on the clipped element are cut off.

Full answer

clip-path cuts an element to a shape. Everything outside the shape is not drawn. Basic shapes are circle(), ellipse(), inset() (a rectangle with optional rounded corners) and polygon(), which takes a list of points as percentages or lengths. There is also path() for curves.

mask-image hides parts of an element by a picture, usually a gradient or an image with transparency. Where the mask is opaque the element shows, and where it is transparent the element is hidden, with smooth steps in between. A fade-out at the bottom of a card is one line: mask-image: linear-gradient(black, transparent).

The main difference: clip-path makes sharp edges and a fixed shape, while mask-image can fade, because it uses the transparency of an image.

Hit testing follows clip-path. The clipped-away area does not receive mouse clicks or hover, so a circle-clipped button is only clickable inside the circle. A shadow on the same element is clipped as well, so put box-shadow on a wrapper.

Older browsers may need the -webkit- prefix for mask. Check the support table for your audience.

The first shape is a circle. The second is a triangle with its tip at the top centre. The blue block fades from fully visible at the top to invisible at the bottom. The teal square is placed under the circle's top-left corner. Because the circle's corner is clipped away, a click there reaches the teal square, not the circle.

For responsive shapes, use percentages, and for complex outlines, create the shape in an SVG and reuse its path.

html
<style>
  body { margin: 0; }
  .shape { width: 100px; height: 100px; background: tomato; margin: 8px; display: inline-block; }
  .circle { clip-path: circle(50%); }
  .triangle { clip-path: polygon(50% 0, 100% 100%, 0 100%); }
  .fade {
    width: 200px; height: 80px; background: #0a6cff;
    -webkit-mask-image: linear-gradient(black, transparent);
    mask-image: linear-gradient(black, transparent);
  }
  .under { position: absolute; top: 8px; left: 8px; width: 100px; height: 100px; background: teal; }
</style>
<div class="under" id="under"></div>
<div class="shape circle" id="circle"></div>
<div class="shape triangle" id="tri"></div>
<div class="fade" id="fade"></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

  • clip-path uses circle(), inset(), polygon() and path() for hard edges.
  • mask-image uses an image or gradient and can fade.
  • Clipped-away areas do not receive clicks or hover.
  • Put box-shadow on a wrapper of a clipped element.
  • Check whether the -webkit- prefix is needed for mask in your target browsers.

Common mistakes

  • Putting a box-shadow on the element that has clip-path, so the shadow is cut off. Put the shadow on a wrapper.
  • Expecting a clipped-away area to still be clickable. It is not.
  • Using fixed pixel points in polygon() for shapes that must scale with the box.

Follow-ups

  • How do you add a shadow to a clipped shape?
  • How would you fade the bottom of a long text block with CSS only?

Tips

  • Contrast the two: clip-path is a hard shape, mask-image can fade.
  • Mention hit testing. Few candidates know the clipped area is not clickable.
76.html-css-0076Mediummid

What do color-mix() and oklch() add to CSS color, and how do you use them with a fallback?

color-mix() blends two colors in a chosen color space, so shades can be derived from one brand color. oklch() describes color by lightness, chroma and hue with more even perceived brightness than hsl(). Provide a plain fallback value before the newer declaration.

Full answer

Two newer parts of CSS color make theming easier.

color-mix() mixes two colors in a chosen color space: color-mix(in srgb, #0a6cff 30%, white) gives a lighter tint made of 30 percent blue and 70 percent white. You can build hover and disabled shades from one brand color without picking each by hand, and the result updates when the brand variable changes.

oklch() describes color by lightness, chroma (how colorful) and hue. Its lightness matches how people see brightness better than hsl() does, so two colors with the same lightness number look about equally bright. That makes accessible palettes easier to plan. It can also express colors outside the old sRGB range on screens that support them. Another new feature, relative color syntax, such as oklch(from var(--brand) calc(l + 0.1) c h), computes a variant of an existing color, but it is newer still.

Because these are newer, give a fallback. A normal declaration before the new one works, because browsers drop declarations they do not understand and keep the earlier value. A feature query is also possible: @supports (color: color-mix(in srgb, red, blue)).

The button gets a lighter blue on hover, made from the brand variable. The panel uses a 10 percent tint where color-mix() is understood and a plain light blue otherwise. The last box mixes red and blue equally and gives a purple.

When you use any of these, check text contrast on the final color, not only on the base color.

html
<style>
  :root { --brand: #0a6cff; }
  .btn {
    padding: 0.5rem 1rem; border: 0; color: #fff;
    background: #0a6cff;
    background: var(--brand);
  }
  .btn:hover {
    background: #3d8bff;
    background: color-mix(in srgb, var(--brand) 80%, white);
  }
  .tint {
    background: #e6f0ff;
  }
  @supports (color: color-mix(in srgb, red, blue)) {
    .tint { background: color-mix(in srgb, var(--brand) 10%, white); }
  }
  .oklch { background: oklch(0.6 0.2 260); color: #fff; padding: 0.5rem; }
  .purple { background: color-mix(in srgb, red 50%, blue 50%); padding: 0.5rem; }
</style>
<button class="btn" id="btn" type="button">Enrol</button>
<div class="tint" id="tint">Tinted panel</div>
<div class="oklch" id="ok">oklch color</div>
<div class="purple" id="mix">Half red, half blue</div>

Checked in Chrome 156 only. The fallback lines were not run in an older browser. 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

  • color-mix(in srgb, A 30%, B) blends two colors by percentage.
  • oklch() uses lightness, chroma and hue.
  • Derived shades update when the base variable changes.
  • Write a normal value first, then the newer one, or use @supports.
  • Check contrast of the final color.

Common mistakes

  • Using color-mix() with no fallback, so older browsers show no background at all.
  • Choosing hover colors by eye in several files instead of deriving them from one variable.
  • Assuming equal hsl() lightness means equal visual brightness. It does not, which oklch() improves.

Follow-ups

  • How do you give a fallback for a CSS function the browser does not know?
  • Why is oklch useful for building accessible palettes?

Tips

  • Say that you provide a normal value first and the new value after it, as a simple fallback.
  • Explain oklch in one line: lightness, chroma, hue, with more even brightness than hsl.
77.html-css-0077Hardsenior

What does the contain property do, and how can it help performance and layout?

contain tells the browser that an element's layout, paint, size or style effects stay inside it, so the browser can limit recalculation. layout and paint containment change behaviour (formatting context, clipping), and size containment requires a set size. It should be used where measured.

Full answer

contain is a promise to the browser: "what happens inside this element does not affect the outside in this way". With the promise, the browser can skip work. When something inside changes, it can limit recalculation to that box and not the whole page.

The values correspond to kinds of containment:

  • layout: the inside layout does not affect the outside, and outside layout does not reach the inside. As a side effect, the element becomes an independent formatting context. Floats stay inside it and its margins do not collapse with children.
  • paint: nothing is drawn outside the box. Content is clipped to the padding box, like overflow: clip. Descendants that are positioned or fixed use this box as their containing block.
  • size: the element's size does not depend on its content. With no explicit size, it collapses to zero in both directions.
  • inline-size: the same, only for the inline direction. This is what container queries use.
  • style: counters and some properties do not leak out.
  • content is shorthand for layout paint style. strict is size layout paint style.

Uses: a long list of independent cards, a widget that updates often (a ticker or a chart), or third-party embeds. A card with contain: content means a change in one card does not force the browser to re-check the others.

The cost is behaviour changes. Paint containment clips content that overflows, such as a dropdown, a tooltip or a shadow. Size containment hides content from the size, so a box with no set size becomes empty.

The first box has contain: size and no height, so it ignores its 80px child and measures 0 high plus borders. The second box clips the red square at its own edge, so a click on the part below the box misses it. In the third box the float is contained, so the box is 70px high plus borders instead of collapsing.

Apply contain only where you measured a problem. In DevTools, look at style recalculation and layout times before and after.

html
<style>
  body { margin: 0; font-family: sans-serif; }
  .case { margin: 8px; border: 1px solid #999; }
  .size { contain: size; }
  .size p { margin: 0; height: 80px; background: #cde; }
  .paint { contain: paint; position: relative; width: 120px; height: 60px; background: #eee; }
  .paint .abs { position: absolute; top: 40px; left: 0; width: 80px; height: 80px; background: tomato; }
  .layout { contain: layout; }
  .layout .float { float: left; width: 50px; height: 70px; background: #9c9; }
</style>
<div class="case size" id="size"><p>Content with its own height</p></div>
<div class="case paint" id="paint"><div class="abs" id="abs"></div></div>
<div class="case layout" id="layout"><div class="float"></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

  • contain is a promise that limits how much of the page needs recalculation.
  • layout makes an independent formatting context; paint clips to the box.
  • size and inline-size stop the size from depending on content.
  • content is layout paint style; strict adds size.
  • Side effects include clipping and zero size, so measure first.

Common mistakes

  • Using contain: size without giving the element a size, which collapses it to zero.
  • Using contain: paint on a component with dropdowns or tooltips that must overflow, so they get clipped.
  • Adding contain: strict everywhere as a habit, without measuring if it helps.

Follow-ups

  • Which containment type do container queries apply behind the scenes?
  • Why can contain: paint cut off a dropdown?

Tips

  • Define it as a promise to the browser, then name the layout, paint and size types.
  • Link it to container queries, which rely on inline-size containment.
78.html-css-0078Mediummid

How do you load a web font without hurting speed or causing layout jumps?

Declare fonts with @font-face using woff2, pick a font-display value such as swap or optional, preload the key font with crossorigin, subset or use variable fonts, and tune a fallback with size-adjust to limit layout shift.

Full answer

A custom font is a file the browser must download. Until it arrives, the browser has to decide what to show. That choice is controlled by font-display inside @font-face.

  • swap: show text at once in a fallback font, then switch when the font loads. Text is readable early, but the swap can move the layout.
  • block: hide the text for a short period, then swap. This avoids the flash of fallback text but delays reading.
  • fallback: a very short block period and a short swap window. If the font arrives late, the fallback stays.
  • optional: a very short block period, and the browser may not use the font at all on a slow connection. This gives the least movement.

Steps for a good setup:

  1. Use woff2, which is smaller than older formats.
  2. Load only the weights and styles that you use. A variable font can replace several files.
  3. Use unicode-range or a subset so users download only the characters they need.
  4. Preload the most important font with <link rel="preload" as="font" type="font/woff2" crossorigin href="...">. The crossorigin attribute is needed even for fonts on your own domain, or the preloaded file is fetched twice.
  5. Pick a fallback font with similar size. The size-adjust, ascent-override and similar descriptors in @font-face can tune a local fallback to match, which reduces the layout shift when the swap happens.

The heading is drawn first in the adjusted Arial. When brand.woff2 has loaded, it switches to the brand font, and the adjusted fallback keeps the size change small. The font file in this example is a placeholder, so the page shows the fallback.

Test on a throttled network in DevTools and check the layout shift score, not only the look on a fast connection.

html
<style>
  @font-face {
    font-family: "Brand";
    src: url("/fonts/brand.woff2") format("woff2");
    font-weight: 400;
    font-style: normal;
    font-display: swap;
  }
  @font-face {
    font-family: "Brand Fallback";
    src: local("Arial");
    size-adjust: 105%;
    ascent-override: 92%;
  }
  body { font-family: "Brand", "Brand Fallback", sans-serif; }
</style>
<link rel="preload" as="font" type="font/woff2" crossorigin href="/fonts/brand.woff2">
<h1 id="h">Learn on Schoolabe</h1>

The font file is a placeholder, so the page shows the fallback font. The check read the @font-face rule, the preload link and the font family in use. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • font-display decides what shows while the font loads.
  • swap shows fallback text first; optional may skip the font on slow networks.
  • Preload important fonts with crossorigin.
  • Use woff2, subsets and variable fonts to cut size.
  • size-adjust and ascent-override tune a fallback to reduce layout shift.

Common mistakes

  • Preloading a font without crossorigin, so the browser downloads it twice.
  • Shipping five weights of a font when the design uses two.
  • Using font-display: block for body text, which leaves a blank page on slow networks.

Follow-ups

  • Why does a font preload need the crossorigin attribute?
  • When would you choose font-display: optional?

Tips

  • Name the four common font-display values and what the user sees for each.
  • Mention fallback metric overrides as the reason that swap does not need to cause a big jump.
79.html-css-0079Mediummid

How does writing-mode change layout, and when would you use vertical text?

writing-mode sets whether lines run horizontally or vertically and which way blocks stack. It changes the inline and block axes, so logical properties follow it. Use it for vertical scripts and side labels, and prefer it over transform: rotate() when layout must adapt.

Full answer

writing-mode sets the direction in which lines of text are laid out and the direction in which blocks stack. The default is horizontal-tb: text runs left to right, and blocks stack top to bottom. With vertical-rl text runs top to bottom and new lines move toward the left. With vertical-lr they move toward the right.

This changes the meaning of "inline" and "block". The inline axis is the direction of the text. The block axis is where the next line goes. This is why logical properties such as inline-size and margin-inline follow the writing mode, and width and margin-left do not.

Uses:

  • Languages such as Japanese and Chinese are traditionally written vertically in some designs. Mongolian is vertical by script.
  • A short label along the side of a card or table header, such as "Sponsored" rotated to read upward.
  • Layout effects such as a vertical heading on the side of an article.

text-orientation: mixed is the default and keeps Latin letters sideways in vertical text. text-orientation: upright makes each letter stand up, which suits short strings. Do not use it for long English text, because it is hard to read.

Do not use transform: rotate() for a vertical label if you want layout to adapt: a rotated box keeps its original layout size. writing-mode changes the real size and the flow.

The first label reads top to bottom, and its box is tall and narrow, about one line wide. The row uses align-items: flex-start so the boxes keep their own size. The second shows each letter upright, one under the other. In the third, the rotated text looks vertical, but the grey parent box still has the width of the horizontal text, because the transform does not change layout.

Check the line direction with your content. Also test with real text from the target language when it matters.

html
<style>
  .row { display: flex; align-items: flex-start; gap: 16px; font: 16px/1.4 sans-serif; }
  .label { writing-mode: vertical-rl; background: #cde; padding: 4px; }
  .upright { writing-mode: vertical-rl; text-orientation: upright; background: #fdc; padding: 4px; }
  .rotated { transform: rotate(90deg); background: #dfc; display: inline-block; }
  .box { background: #eee; }
</style>
<div class="row">
  <span class="label" id="label">Sponsored</span>
  <span class="upright" id="up">ABC</span>
  <span class="box"><span class="rotated" id="rot">Sponsored</span></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

  • horizontal-tb is the default; vertical-rl and vertical-lr stack lines sideways.
  • writing-mode redefines the inline and block axes.
  • text-orientation: upright stands each letter up.
  • transform: rotate() does not change layout size.
  • Use logical properties to keep layouts working in any mode.

Common mistakes

  • Rotating text with transform and then fighting overlap, because layout still uses the unrotated size.
  • Using text-orientation: upright for long Latin text.
  • Mixing physical properties like width and margin-left in a vertical layout instead of logical ones.

Follow-ups

  • What is the difference between vertical-rl and vertical-lr?
  • Why does a rotated element still take its old space?

Tips

  • State that writing-mode redefines the inline and block axes.
  • Say why logical properties exist, and tie it back to writing-mode.
80.html-css-0080Hardsenior

Cards in a grid have titles of different length, so their buttons do not line up. How does subgrid fix this?

subgrid lets a nested grid reuse its parent's rows or columns, so items inside separate cards line up across the whole row. Make each card span the rows and set grid-template-rows: subgrid. Keep a flex fallback with @supports because subgrid is newer.

Full answer

When each card is its own grid or flex box, the card does not know about its neighbours. The title of one card can take two lines and another one line, so the content below starts at different heights.

subgrid lets a nested grid use the rows or columns of its parent grid instead of making its own. If every card spans three parent rows and uses grid-template-rows: subgrid, then the first row is shared by all titles in that row. The row height is the tallest title, and the text and buttons below line up across all cards.

Steps:

  1. The parent grid defines the columns. The cards flow into columns.
  2. Each card spans a number of rows with grid-row: span 3, and itself is display: grid; grid-template-rows: subgrid.
  3. The card's children take the rows in order: title, text, button.
  4. gap is inherited from the parent by default, and the card can override it.

Without subgrid, the older fixes are fixed heights (fragile), JavaScript measuring, or a flex column with margin-top: auto on the button. The last one is a good simple solution when only the bottom needs to line up. Subgrid is better when several rows, such as title, price and list, should align.

Subgrid is a newer feature. Check the support table, and keep a simple fallback with @supports (grid-template-rows: subgrid).

All three buttons start at the same height, and all three paragraphs start at the same height, even though the second title is much longer. Where subgrid is not supported, the flex fallback still pushes the buttons to the bottom of equal-height cards.

Keep in mind that the card's content is placed into rows of the parent, so a card that has more children than rows will create extra implicit rows in the parent.

html
<style>
  body { font-family: sans-serif; margin: 0; }
  .cards { display: grid; grid-template-columns: repeat(3, 120px); gap: 8px 12px; }
  .card { border: 1px solid #999; padding: 8px; display: flex; flex-direction: column; }
  .card button { margin-top: auto; }
  @supports (grid-template-rows: subgrid) {
    .card { display: grid; grid-row: span 3; grid-template-rows: subgrid; gap: 4px; }
    .card button { margin-top: 0; align-self: start; }
  }
  h3 { margin: 0; font-size: 16px; }
  p { margin: 0; }
</style>
<div class="cards">
  <div class="card" id="c1"><h3 id="t1">Short</h3><p id="p1">Text</p><button id="b1">Go</button></div>
  <div class="card" id="c2"><h3 id="t2">A much longer title that wraps across lines</h3><p id="p2">Text</p><button id="b2">Go</button></div>
  <div class="card" id="c3"><h3 id="t3">Medium title here</h3><p id="p3">Text</p><button id="b3">Go</button></div>
</div>

Checked in Chrome 156 only, where subgrid is available. The flex fallback was not run separately in an older browser. 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

  • Nested cards normally cannot align content with neighbouring cards.
  • grid-template-rows: subgrid shares the parent's row tracks.
  • The card must span the rows with grid-row: span N.
  • A flex column with margin-top: auto is a simple fallback.
  • Check the support table and use @supports.

Common mistakes

  • Giving each card a fixed height to align content, which breaks when text grows or the page is zoomed.
  • Forgetting grid-row: span N on the card, so the card sits in one row and the subgrid has nothing to share.
  • Using subgrid with no fallback and no support check.

Follow-ups

  • How does a subgrid get its gap?
  • When is margin-top: auto in a flex column enough?

Tips

  • Explain the root problem first: nested boxes cannot see their neighbours.
  • Mention the flex margin-top: auto fallback, and say when it is enough.