← Interview prep

HTML & CSS interview questions

Semantic HTML, CSS layout, and CSS interview depth.

193 questions · Page 2 of 10

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

Page 2 of 10

Questions 21–40 of 193 · 0 of 20 on this page marked learned

21.html-css-0021Easyfresher

How do CSS transforms and transitions work together?

A transform moves, rotates, scales or skews an element after layout, without changing the space of other elements. A transition animates a property from one value to another over a duration when its value changes, for example on hover. Together they make small interface motion; transform and opacity are usually the cheapest to animate.

Full answer

A transform changes how a box is drawn (move, rotate, scale, skew) without changing the layout. Other elements do not move, because the original space is still reserved. A transition tells the browser to animate a property over time when its value changes, instead of jumping.

A transition needs four things: which property, how long, how it speeds up (timing function) and an optional delay. They are written transition: transform 0.2s ease-out 0s. The change usually comes from a state such as :hover, :focus-visible or a class added by JavaScript.

Hover over the button and it grows by 10 percent over 0.2 seconds. Move the mouse away and it shrinks back over the same time, because the transition is declared on the base state.

Transform functions are applied right to left in the order written, so translateX(100px) rotate(45deg) is not the same as rotate(45deg) translateX(100px). The transform-origin property sets the pivot point, and it defaults to the centre of the box.

Transitions cannot animate from or to display: none in the normal way, and auto heights do not animate. Animating transform and opacity is usually cheapest because browsers can often handle them without recomputing layout.

html
<style>
  button {
    padding: 0.6rem 1.2rem; border: 0; background: #0a6cff; color: #fff; border-radius: 6px;
    transform: scale(1);
    transition: transform 0.2s ease-out, box-shadow 0.2s ease-out;
  }
  button:hover, button:focus-visible { transform: scale(1.1); box-shadow: 0 4px 10px rgba(0,0,0,.3); }
</style>
<button id="b">Buy now</button>

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

  • Transform changes how a box is drawn, not the layout.
  • A transition needs the property, duration, timing function and optional delay.
  • Put the transition on the base state so it also runs on the way back.
  • Transform order matters because functions apply right to left.
  • Avoid transition: all and animate transform and opacity where you can.

Common mistakes

  • transition: all. It animates things you did not intend, such as layout properties, and it makes later changes harder to reason about. List the properties.
  • forgetting that transform on an element makes it a containing block for fixed-position children and creates a stacking context.

Follow-ups

  • transition or keyframes animation?
  • Why does a transform create a stacking context?
  • How do you animate an element in from display: none?

Tips

  • Put the transition on the base rule, not only on :hover, if you want the return animation too.
  • Describe the hover button example: base state, hover state, transition on base.
  • Mention reduced motion preferences when you talk about animation.
22.html-css-0022Easyfresher

How do inline, block and inline-block elements differ in CSS?

A block box starts on a new line and fills the available width. An inline box flows within a line of text and ignores width, height and vertical margin. An inline-block box flows like inline but accepts width, height and all margins. Whitespace between inline-blocks creates small gaps.

Full answer

display controls how a box takes part in the flow of the page.

A block box starts on a new line and stretches across the full width of its parent. You can set width, height, margin and padding on all four sides. Examples: div, p, h1, section.

An inline box sits inside a line of text, like a word. It is only as wide as its content. width and height are ignored, and vertical margin does not push other lines away. Vertical padding paints but does not change the line height. Examples: span, a, em.

An inline-block box sits in a line like an inline box, but inside it behaves like a block. It accepts width, height and all margins.

In Chrome the inline span is not 200px wide (its width is only the text), the inline-block span is exactly 200px by 100px, and the block span is 200px by 100px and sits on its own line.

Two inline-block boxes written on separate lines in HTML have a small gap between them. That gap is the whitespace between the tags, treated as a space character. Flexbox does not have this problem, which is one reason it replaced inline-block for rows of boxes.

html
<style>
  body { margin: 0; font: 16px/1.4 sans-serif; }
  .tag { width: 200px; height: 100px; margin-top: 20px; background: #cde; }
  #i { display: inline; }
  #ib { display: inline-block; }
  #b { display: block; }
</style>
<p>
  <span class="tag" id="i">inline</span>
  <span class="tag" id="ib">inline-block</span>
  <span class="tag" id="b">block</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

  • block: new line, full width, all box properties apply.
  • inline: sits in the text flow and ignores width, height and vertical margin.
  • inline-block: inline placement with block sizing.
  • Whitespace between inline-blocks becomes a visible gap.
  • Flexbox and grid replaced inline-block for rows of boxes.

Common mistakes

  • setting width and height on a span or a and wondering why nothing happens. Change display or use a flex or grid parent.
  • treating the gap between inline-block elements as a margin bug. It is whitespace, and font-size: 0 on the parent or flex is the clean fix.

Follow-ups

  • what does display: contents do?
  • What does display: contents do?
  • Why does setting width on an anchor not work until you change display?

Tips

  • Use inline-block for small things that sit in a line of text, such as a badge with fixed padding. For whole rows of cards, use flexbox or grid.
  • Name two example elements for each type: span, div, and a small badge for inline-block.
  • Mention the whitespace gap; it is the detail that proves hands-on experience.
23.html-css-0023Easyfresher

What is semantic HTML, and why use header, nav, main and footer instead of div?

Semantic HTML uses elements that describe meaning, such as header, nav, main, article, aside and footer, instead of generic divs. It gives screen reader users landmarks to jump between, helps search engines and tools understand structure, and keeps code readable. Native elements like button also bring keyboard behaviour for free.

Full answer

Semantic HTML means choosing the element that describes the meaning of the content, not only how it looks. A nav says "this is a group of navigation links". A div says nothing.

The common structural elements are:

  • header: introductory content for the page or a section, such as a logo and title.
  • nav: a main block of navigation links.
  • main: the central content of the page. Use only one visible main per page.
  • article: a self-contained piece, such as a blog post or a news card, that makes sense on its own.
  • section: a themed group of content, normally with a heading.
  • aside: related content beside the main flow, like a sidebar.
  • footer: closing content such as copyright and contact links.
  • figure and figcaption: an illustration with its caption.

Why it matters. Screen readers list these as landmarks, so a user can jump straight to the navigation or the main content. Search engines and other tools understand the page structure better. Developers read the code faster. Some elements also come with free behaviour: button is focusable and works with Enter and Space, while a div with a click handler does neither.

In the accessibility tree this page exposes banner, navigation, main, complementary and contentinfo landmarks. Use div and span when no element fits, for example a wrapper that exists only for styling.

html
<header>
  <h1>Greenfield College</h1>
  <nav aria-label="Main">
    <ul><li><a href="/courses">Courses</a></li><li><a href="/fees">Fees</a></li></ul>
  </nav>
</header>
<main>
  <article>
    <h2>Admissions open for 2027</h2>
    <p>Applications close on <time datetime="2027-03-31">31 March 2027</time>.</p>
    <figure>
      <img src="campus.jpg" width="600" height="300" alt="Main building of the college">
      <figcaption>The main building</figcaption>
    </figure>
  </article>
  <aside aria-label="Related">Scholarship details</aside>
</main>
<footer><p>Contact: office@greenfield.example</p></footer>

Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • Use element names that describe the content: header, nav, main, article, section, aside, footer.
  • Landmarks let screen reader users jump to navigation or main content.
  • Use one main per page.
  • Use div and span only when no semantic element fits.
  • Native elements bring behaviour, like a button's keyboard support.

Common mistakes

  • wrapping everything in div and span, then adding role attributes to repair it. Use the right element first.
  • using section as a generic wrapper. If it has no heading and no clear theme, a div is more honest.

Follow-ups

  • when is a header a banner landmark?
  • What is the difference between article and section?
  • Why is a nav element often given an aria-label?

Tips

  • Check your structure by turning off CSS or by using a screen reader landmark list. If the page makes sense as a plain outline, the semantics are good.
  • Walk through a simple page layout and name the element for each region. Keep it to the page you can picture.
  • Say what you would use for a clickable control: a button, never a div with an onclick.
24.html-css-0024Easyfresher

How do you write good alt text for images?

The alt attribute is the text equivalent of an image. Informative images get a short description of what matters, functional images (inside links or buttons) describe the action, and decorative images get an empty alt. Complex images such as charts need a short alt plus full data in nearby text. Never leave alt out.

Full answer

The alt attribute gives an image a text equivalent. Screen readers read it. The browser shows it when the image fails to load. Search engines use it to understand the image.

What to write depends on the job of the image.

  • Informative image: say what a person would learn from seeing it. Keep it short, usually one sentence.
  • Functional image (an image inside a link or button): describe the action, not the picture. A magnifying glass inside a button is "Search".
  • Decorative image: use an empty alt="". Screen readers then skip it. Better still, put purely decorative pictures in CSS as backgrounds.
  • Complex image such as a chart: give a short alt with the main point and put the full data in text or a table nearby.

Do not start with "image of" or "picture of". The screen reader already says it is an image. Do not stuff keywords.

The first image is announced with its meaning. The logo link is announced as "Greenfield College home, link". The divider is skipped. The last image has no alt at all, which is the worst case: many screen readers read out the file name instead.

A useful test: if the image disappeared, what text would you put in its place so the reader still gets the same information? That text is the alt.

html
<img src="results.png" width="500" height="300"
     alt="Bar chart: pass rate rose from 62% in 2023 to 81% in 2025">

<a href="/home"><img src="logo.png" width="120" height="40" alt="Greenfield College home"></a>

<img src="divider.png" width="400" height="10" alt="">

<img src="photo.png" width="300" height="200">

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

  • Informative image: describe the information it carries.
  • Functional image: describe the action or destination.
  • Decorative image: alt="" so screen readers skip it.
  • Complex image: short alt plus a long description in text.
  • Do not start with image of, and do not stuff keywords.

Common mistakes

  • repeating the visible caption in the alt text, so screen reader users hear it twice. Alt should add what the caption does not say.
  • writing alt="image" or the file name. This adds noise and no information.

Follow-ups

  • how long should alt text be?
  • How is alt text different from a figcaption?
  • What happens in a screen reader when alt is missing entirely?

Tips

  • Always include the alt attribute, even when it is empty. A missing alt is an error. An empty alt is a deliberate choice.
  • Use the 'what text would replace this image' test and say it in the answer.
  • Give three examples: a chart, a logo link and a divider.
25.html-css-0025Easyfresher

How do you build an accessible HTML form with labels, input types and fieldsets?

An accessible form gives every control a label connected with for and id, uses the right input type, includes a name attribute so the value is sent, and groups related controls in a fieldset with a legend. Placeholders are not labels. autocomplete values help browsers fill details.

Full answer

A form is a set of controls the user fills in. Four things make a basic form usable for everyone.

  1. A label for each control. Connect it with for (matching the control's id), or wrap the control inside the label. Clicking the label focuses the input, and screen readers announce the label as the control's name. A placeholder is not a label. It disappears as the user types.
  2. The right type. type="email", tel, number, date and password give the right keyboard on phones and some built-in checks.
  3. A name attribute. It is the key that is sent to the server, so a control without name is not submitted.
  4. fieldset and legend for groups, such as a set of radio buttons. The legend becomes the group's name.

Add autocomplete values such as name, email and tel so browsers can fill in details. Use button type="submit" for the submit action.

In the accessibility tree, the two inputs are named "Full name" and "Email address", and the radio buttons are in a group named "Fee plan". Clicking the word "Email address" moves focus into the email box.

Group related fields, keep one question per label, and write labels so they still make sense when read out of context, for example "Email address" rather than just "Email".

html
<form action="/apply" method="post">
  <p>
    <label for="fullname">Full name</label>
    <input id="fullname" name="fullname" type="text" autocomplete="name" required>
  </p>
  <p>
    <label for="email">Email address</label>
    <input id="email" name="email" type="email" autocomplete="email" required>
  </p>
  <fieldset>
    <legend>Fee plan</legend>
    <label><input type="radio" name="plan" value="monthly" checked> Monthly</label>
    <label><input type="radio" name="plan" value="yearly"> Yearly</label>
  </fieldset>
  <button type="submit">Apply</button>
</form>

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

  • Connect label for to input id, or wrap the input in the label.
  • Pick the right input type for keyboard and validation.
  • A control without a name attribute is not submitted.
  • fieldset and legend name groups such as radio sets.
  • A placeholder is not a replacement for a label.

Common mistakes

  • using placeholder text as the only label. It fails contrast checks often, vanishes while typing and may not be announced reliably.
  • leaving out name on an input and then wondering why the server does not receive the value.

Follow-ups

  • what is the difference between GET and POST on a form?
  • What is the difference between a button of type submit and type button?
  • Why does clicking a label focus its input?

Tips

  • Write labels above the inputs on small screens. They stay readable when the keyboard opens and when text is zoomed.
  • Write a short form from memory in the interview: label, input, fieldset, button. It is a common live task.
  • Mention autocomplete values for name, email and address.
26.html-css-0026Easyfresher

How are id and class different in HTML and CSS?

An id names a single element and must be unique in the page. A class names a group, and an element can have several. In CSS, ids are selected with # and have higher specificity, so teams usually style with classes and keep ids for link targets, label connections and ARIA relationships.

Full answer

An id names one element. It must be unique in the page. A class names a group. Many elements can share the same class, and one element can have several classes separated by spaces.

In CSS, an id is selected with # and a class with .. An id selector is more specific than a class selector, so it wins conflicts. That is why most teams style with classes and keep ids for other jobs.

Real uses of an id:

  • A link target. <a href="#fees"> jumps to the element with id="fees".
  • Connecting a label to an input with for.
  • ARIA relationships such as aria-labelledby.
  • A single element picked from JavaScript, for example with document.getElementById.

Two spans share badge and pass, so one rule styles both. The element with id="summary" is unique and is reachable through the link #summary.

When an id is repeated, the HTML is invalid. getElementById returns only the first match, anchors jump to the first, and a label may connect to the wrong input.

html
<style>
  .badge { padding: 2px 8px; border-radius: 4px; color: #fff; }
  .badge.pass { background: seagreen; }
  .badge.fail { background: crimson; }
  #summary { font-weight: bold; }
</style>
<p id="summary">Results</p>
<span class="badge pass" id="b1">Maths</span>
<span class="badge fail" id="b2">Physics</span>
<span class="badge pass" id="b3">Biology</span>
<p><a href="#summary" id="jump">Jump to summary</a></p>
<script>
  document.title = document.querySelectorAll(".badge.pass").length + " passed";
</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

  • id must be unique; class can repeat and be combined.
  • Selectors: #id and .class; id selectors are more specific.
  • Use ids for fragment links, label for and ARIA references.
  • Duplicate ids make getElementById and fragments unreliable.
  • Style with classes to keep specificity low.

Common mistakes

  • copying a block of HTML and forgetting to change its ids, which leaves duplicates.
  • styling with ids and then finding that a later class cannot override them without !important.

Follow-ups

  • can an id contain spaces?
  • Can one element have more than one class?
  • How would you find all elements with a class in JavaScript?

Tips

  • Use classes for styling, ids for targets and relationships. Naming classes after purpose (badge, card) is easier to maintain than naming after look (red-text).
  • State the simple rule: classes for styling, ids for targets.
  • Bring up the specificity side effect; it shows you know why classes are preferred.
27.html-css-0027Easyfresher

How do relative and absolute URLs work in links, and when should you use target="_blank" with rel?

An absolute URL has scheme and host, a root-relative URL starts with a slash, and a relative URL is resolved from the current page's folder. The browser converts all of them to full URLs using the page as the base. target="_blank" opens a new tab, and rel="noopener noreferrer" is a safe habit for external links.

Full answer

A link's href can be written three ways.

  • Absolute URL: the full address with scheme and host, such as https://example.com/courses/css.html. It works from anywhere.
  • Root-relative: begins with /, such as /courses/css.html. It starts from the site's root.
  • Relative: no leading slash, such as css.html, ./css.html or ../index.html. It is resolved from the folder of the current page. .. means one folder up.

A fragment such as #fees jumps inside the page. Other schemes, such as mailto: and tel:, open the mail or phone app.

The browser turns every URL into a full one with the current page as the base. This script shows how:

The output is:

next.html -> https://school.example/courses/css/next.html ./next.html -> https://school.example/courses/css/next.html ../index.html -> https://school.example/courses/index.html /fees -> https://school.example/fees #top -> https://school.example/courses/css/lesson.html#top https://other.example/x -> https://other.example/x

target="_blank" opens a new tab. Without precautions the new page could get access to window.opener. Current browsers treat target="_blank" links as noopener by default, but writing rel="noopener" is still a harmless habit that also covers older browsers. noreferrer also hides the page address from the destination. Tell users when a link opens in a new tab, for example with visible text or an icon with a text label.

html
<pre id="out"></pre>
<script>
  const base = "https://school.example/courses/css/lesson.html";
  const links = ["next.html", "./next.html", "../index.html", "/fees", "#top", "https://other.example/x"];
  document.getElementById("out").textContent =
    links.map(l => l + " -> " + new URL(l, base).href).join("\n");
</script>
<a href="https://other.example" target="_blank" rel="noopener noreferrer">External site</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

  • Absolute, root-relative and relative links resolve differently.
  • The .. segment moves one folder up.
  • A fragment like #fees links within the page.
  • target="_blank" with rel="noopener" protects against window.opener access.
  • The base element changes how every relative link resolves.

Common mistakes

  • using ../ paths in templates that are reused at different folder depths, which then break on some pages.
  • using target="_blank" for every link. It takes control away from users, and for screen reader users a new tab can be disorienting.

Follow-ups

  • what does the base element do?
  • What does rel="noreferrer" change?
  • Why do relative links break when a template moves to another folder depth?

Tips

  • Use root-relative or relative links for pages on your own site so the same code works on staging and production.
  • Show the new URL(link, base) trick to prove your answer; it is quick and exact.
  • Mention that new tabs should be announced to users.
28.html-css-0028Easyfresher

What does the viewport meta tag do, and why is it needed for responsive pages?

Mobile browsers pretend the page is about 980 pixels wide unless told otherwise. The viewport meta tag with width=device-width, initial-scale=1 makes layout use the real device width, so media queries and fluid layouts behave properly. Do not disable user zoom; it harms accessibility.

Full answer

Phones were designed to show pages built for desktop screens. To make those pages usable, a mobile browser lays out the page on a virtual screen about 980 CSS pixels wide, and then shrinks it to fit the real screen. The text is tiny and media queries based on width do not match what you expect.

The viewport meta tag tells the browser to use the real device width as the layout width instead:

On a phone that is 390 CSS pixels wide, this page reports 390 and the min-width: 600px rule stays off. If you remove the meta tag, a phone usually reports about 980, because it falls back to the virtual width, and the page appears zoomed out.

width=device-width sets the layout width to the device width. initial-scale=1 sets the first zoom level to 100 percent. Do not add user-scalable=no or a small maximum-scale. Pinch zoom is an accessibility feature for people with low vision, and blocking it fails accessibility guidelines.

The tag only affects mobile browsers. Desktop browsers ignore it, which is why a responsive page can look fine on a laptop and wrong on a phone when the tag is missing.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Viewport demo</title>
  <style>
    body { margin: 0; font: 16px/1.5 sans-serif; }
    .box { padding: 1rem; background: #e8eefc; }
    @media (min-width: 600px) { .box { background: #fde9c9; } }
  </style>
</head>
<body>
  <div class="box" id="box">Layout width: <span id="w"></span> CSS px</div>
  <script>document.getElementById("w").textContent = window.innerWidth;</script>
</body>
</html>

This is a complete page. In Chrome mobile emulation at 390px wide it reported 390 with the tag and 980 without it.

Key points

  • Without the tag mobile browsers lay out at a wide virtual width and scale down.
  • width=device-width uses the real device width in CSS pixels.
  • initial-scale=1 sets the first zoom level to 100 percent.
  • Avoid user-scalable=no and tiny maximum-scale values.
  • Desktop browsers ignore the tag.

Common mistakes

  • testing responsive layouts only by resizing a desktop window. Use the DevTools device mode, which honours the meta tag, and test on a real phone.
  • disabling zoom with user-scalable=no to stop layout shifts. Fix the layout instead.

Follow-ups

  • what are CSS pixels?
  • What is the device pixel ratio?
  • Why might a page look fine on a laptop but wrong on a phone?

Tips

  • Make the tag part of your base template so no page forgets it.
  • Put the tag in your base template and say so in the answer.
  • Explain a CSS pixel in one line; it often comes next.
29.html-css-0029Easyfresher

How do you structure an accessible HTML table?

Use tables for data in rows and columns, not for layout. A good table has a caption, thead, tbody and optional tfoot, th for header cells and td for data, and scope attributes so assistive technology links headers to cells. Wide tables can scroll inside a wrapper on small screens.

Full answer

Use a table for data that has rows and columns, such as marks, timetables or prices. Do not use it for page layout. Use CSS for layout.

A well-built table has:

  • caption: the title of the table, announced by screen readers.
  • thead, tbody and optionally tfoot: group header rows, body rows and summary rows.
  • th for header cells and td for data cells.
  • scope="col" on column headers, and scope="row" on row headers, so assistive tools know which cells each header describes.

A screen reader user on the cell with 64 hears something like "Physics, Marks, 64", because the row and column headers are linked. The table is announced with its caption, "Term 1 marks".

For very wide tables on small screens, wrap the table in a block with overflow-x: auto so the page itself does not scroll sideways. For complex tables with merged cells (colspan, rowspan), use id and headers attributes, or consider splitting into simpler tables.

html
<style>
  table { border-collapse: collapse; }
  th, td { border: 1px solid #999; padding: 6px 12px; text-align: left; }
  tfoot th, tfoot td { font-weight: bold; }
</style>
<table>
  <caption>Term 1 marks</caption>
  <thead>
    <tr><th scope="col">Subject</th><th scope="col">Marks</th><th scope="col">Out of</th></tr>
  </thead>
  <tbody>
    <tr><th scope="row">Maths</th><td>78</td><td>100</td></tr>
    <tr><th scope="row">Physics</th><td>64</td><td>100</td></tr>
  </tbody>
  <tfoot>
    <tr><th scope="row">Total</th><td>142</td><td>200</td></tr>
  </tfoot>
</table>

Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • Tables are for tabular data; use CSS for layout.
  • caption names the table; thead, tbody and tfoot group rows.
  • th is for headers; scope="col" and scope="row" connect them to cells.
  • border-collapse: collapse gives single borders.
  • Wrap wide tables in a scrolling container instead of scrolling the page.

Common mistakes

  • using td with bold text instead of th for headers. It looks the same but carries no meaning.
  • building page layouts with tables. They do not adapt to screen sizes and make the reading order confusing.

Follow-ups

  • what is the difference between th scope="col" and scope="row"?
  • What do colspan and rowspan do?
  • How would you make a wide table usable on a phone?

Tips

  • Use border-collapse: collapse for a single clean border between cells. By default each cell draws its own.
  • Write a small marks table from memory including caption and scope.
  • Mention that complex tables with merged cells need headers and id attributes.
30.html-css-0030Easyfresher

What are the CSS combinators: descendant, child, adjacent sibling and general sibling?

Combinators describe how two selectors are related in the tree: a space means any descendant, > a direct child, + the next adjacent sibling and ~ any following sibling. Attribute selectors such as [type="email"] and [href^="https"] add matching by attributes. Siblings only look forward; :has() is needed to look back.

Full answer

A combinator is the symbol between two selectors that says how the elements must be related in the HTML tree.

  • Descendant (a space): nav a matches any a inside a nav, at any depth.
  • Child (>): ul > li matches an li that is a direct child of ul. Grandchildren are excluded.
  • Adjacent sibling (+): h2 + p matches a p that comes immediately after an h2 with the same parent.
  • General sibling (~): h2 ~ p matches every p that comes after an h2 with the same parent, not necessarily right after it.

.menu > li draws a border around the outer li only. The inner li is a grandchild of .menu, so it is not matched. (A border is not inherited, which makes the effect easy to see. Something like font-weight would pass down to the inner item anyway.) The adjacent rule colours only the first paragraph, while the general sibling rule underlines both. The link matches nav a and a[href^="https"], and green wins because the attribute selector adds a class-level point to the score, not because it comes later.

Attribute selectors are close relatives. [type="email"] is an exact match, [href^="https"] means starts with, [href$=".pdf"] ends with, and [class*="btn"] contains.

html
<style>
  nav a            { color: navy; }
  .menu > li       { border: 1px solid #999; }
  h2 + p           { color: crimson; }
  h2 ~ p           { text-decoration: underline; }
  input[type="email"] { border: 2px solid teal; }
  a[href^="https"] { color: green; }
</style>
<nav><ul class="menu">
  <li id="outer">Courses
    <ul><li id="sub"><a href="https://example.com" id="link">Python</a></li></ul>
  </li>
</ul></nav>
<h2>Notice</h2>
<p id="p1">First paragraph</p>
<p id="p2">Second paragraph</p>
<input type="email" id="mail">

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

  • Descendant (space) matches at any depth; child (>) only direct children.
  • + matches the very next sibling; ~ matches all later siblings.
  • Attribute selectors can match exactly, by prefix, suffix or substring.
  • CSS siblings only look forward.
  • Prefer short class selectors to long descendant chains.

Common mistakes

  • expecting + to select an element that comes before. CSS siblings only look forward. The :has() selector is the tool for looking at earlier or surrounding elements.
  • using long descendant chains such as .page .content .list .item a. They are brittle and hard to override. Use a class on the element.

Follow-ups

  • how do you select a parent based on its child?
  • What is the difference between h2 + p and h2 ~ p?
  • How do you select every link that ends with .pdf?

Tips

  • Prefer the child combinator when you want to limit how far a style reaches. It keeps nested components from picking up each other's rules.
  • Run through one HTML snippet and say which selector matches which element. That is how this question is usually asked.
  • Mention :has() when asked about selecting a parent or earlier sibling.
31.html-css-0031Easyfresher

What are the different ways to centre an element horizontally and vertically in CSS?

Centring depends on the element. Text uses text-align: center, a block with a width uses margin-inline: auto, and for both axes grid with place-items: center is shortest for one child, while flexbox with justify-content and align-items suits several children. Absolute positioning with inset: 0 and margin: auto, or top and left 50 percent with translate, also works.

Full answer

There is no single way, because the right method depends on the element. These are the usual ones.

  • Text and inline content: text-align: center on the parent centres it horizontally.
  • A block with a set width: margin-inline: auto centres it horizontally.
  • Flexbox: display: flex; justify-content: center; align-items: center on the parent centres children both ways.
  • Grid: display: grid; place-items: center is the shortest form for one child.
  • Absolute positioning: position: absolute; inset: 0; margin: auto works for an element with known size, and top: 50%; left: 50%; transform: translate(-50%, -50%) works for unknown size.

The parent needs a height for vertical centring to be visible.

In Chrome the first four dots have their centre at exactly (100, 50) inside the 200 by 100 frame. In the fifth frame, margin: 40px auto 0 centres the dot horizontally only. Auto margins on a block do not centre vertically in normal flow, but they do inside a flex or grid container.

For new work, choose grid place-items: center for a single child, or flexbox when there are several children to line up.

html
<style>
  .row { display: flex; flex-wrap: wrap; gap: 10px; }
  .frame { position: relative; width: 200px; height: 100px; background: #eee; }
  .dot { width: 40px; height: 20px; background: tomato; }
  .flex { display: flex; justify-content: center; align-items: center; }
  .grid { display: grid; place-items: center; }
  .abs .dot { position: absolute; inset: 0; margin: auto; }
  .tr .dot { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
  .auto .dot { margin: 40px auto 0; }
</style>
<div class="row">
  <div class="frame flex" id="f1"><div class="dot"></div></div>
  <div class="frame grid" id="f2"><div class="dot"></div></div>
  <div class="frame abs" id="f3"><div class="dot"></div></div>
  <div class="frame tr" id="f4"><div class="dot"></div></div>
  <div class="frame auto" id="f5"><div class="dot"></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

  • text-align: center for inline content; margin-inline: auto for a block with a width.
  • Flex: justify-content and align-items on the parent.
  • Grid: place-items: center on the parent.
  • Absolute: inset: 0 and margin: auto, or top/left 50 percent with translate(-50%, -50%).
  • The parent needs a height to see vertical centring.

Common mistakes

  • using margin: 0 auto on an element with no width. A block with width: auto already fills the line, so there is nothing to centre.
  • vertical centring with height: 100vh without checking mobile browser toolbars. Use min-height and consider dvh units, then check support.

Follow-ups

  • why does vertical-align: middle not centre a div?
  • Why does vertical-align: middle not centre a div?
  • How would you centre an element inside the full viewport?

Tips

  • Memorise two methods: place-items: center on a grid and margin-inline: auto for a block with a width. Those cover most real cases.
  • Give the shortest working answer first (grid, place-items), then list others only if asked.
  • State the one requirement: the parent needs a height.
32.html-css-0032Mediummid

How does built-in HTML form validation work, and when do you need the Constraint Validation API?

Browsers validate forms from attributes such as required, type, min, max, minlength and pattern, and expose the result through the validity object, checkValidity and reportValidity. The Constraint Validation API, with setCustomValidity, covers rules attributes cannot express, like matching passwords. Browser validation is a convenience; the server must validate again.

Full answer

Browsers can check form values without any JavaScript. You describe the rules with attributes, and the browser blocks submission and shows a message when a rule fails.

Useful attributes: required, type (email, url, number), min and max, minlength and maxlength, step and pattern (a regular expression the whole value must match). Each control has a validity object with flags such as valueMissing, typeMismatch, patternMismatch, tooShort, rangeUnderflow and customError. checkValidity() returns true or false, and reportValidity() also shows the message.

The Constraint Validation API is the scripting side. Use it when the rule cannot be written as an attribute, such as "confirm password must match password". Call setCustomValidity("message") to mark a field invalid, and setCustomValidity("") to clear it.

Typing abc in the email box sets typeMismatch, 12 in the age box sets rangeUnderflow, abc12 in the roll number box sets patternMismatch, and mismatching passwords set a customError with the message you wrote. When the values are corrected, checkValidity() returns true.

Validation in the browser is for convenience only. Anyone can bypass it, so the server must validate again. Style states with :invalid and :valid, but remember :invalid matches before the user has typed anything. A newer :user-invalid pseudo-class waits for interaction. Check the support tables before depending on it.

html
<form id="f">
  <label for="name">Name</label>
  <input id="name" name="name" required minlength="2">
  <label for="email">Email</label>
  <input id="email" name="email" type="email" required>
  <label for="age">Age (16 to 60)</label>
  <input id="age" name="age" type="number" min="16" max="60">
  <label for="code">Roll number (3 capital letters, 3 digits)</label>
  <input id="code" name="code" pattern="[A-Z]{3}[0-9]{3}" title="Example: ABC123">
  <label for="pw">Password</label>
  <input id="pw" name="pw" type="password" minlength="8" required>
  <label for="pw2">Repeat password</label>
  <input id="pw2" type="password" required>
  <button type="submit">Register</button>
</form>
<script>
  const pw = document.getElementById("pw"), pw2 = document.getElementById("pw2");
  function match() { pw2.setCustomValidity(pw.value === pw2.value ? "" : "Passwords do not match"); }
  pw.addEventListener("input", match);
  pw2.addEventListener("input", match);
</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

  • Built-in rules: required, type, min, max, minlength, maxlength, step, pattern.
  • validity flags tell which rule failed; checkValidity returns true or false.
  • setCustomValidity marks a field invalid and an empty string clears it.
  • :invalid matches before any typing; :user-invalid waits for interaction.
  • Always validate on the server as well.

Common mistakes

  • trusting browser validation and skipping the server check. The browser rules can be removed in DevTools or by sending a request by hand.
  • forgetting to clear a custom error with setCustomValidity(""). The field then stays invalid forever.

Follow-ups

  • what does the novalidate attribute on a form do?
  • What does the novalidate attribute do?
  • How would you show a custom error message next to a field?

Tips

  • Put a clear text hint near the field (format, limits) before the user makes an error. The title attribute is not shown on touch screens.
  • Explain what you do for a confirm password field: custom validity cleared on each input.
  • Say clearly that client validation is not security.
33.html-css-0033Mediummid

When should you use ARIA, and what are the basic rules for using it correctly?

ARIA adds roles, states and properties to the accessibility tree but gives no behaviour. The first rule is to use a native element when one exists. Use ARIA for what HTML lacks, such as aria-expanded on a disclosure or a live region, keep states in sync with script, and make every ARIA control keyboard operable and named.

Full answer

ARIA is a set of attributes that adds meaning to the accessibility tree: roles (what something is), states (aria-expanded, aria-checked) and properties (aria-label, aria-controls). It changes only what assistive technology hears. It does not add behaviour, focus or keyboard support.

The first rule of ARIA: if a native HTML element already has the meaning and behaviour you need, use it. A button is better than div role="button", because the native one is focusable, reacts to Enter and Space, and is announced correctly with no extra work.

The basic rules are:

  1. Prefer native elements to ARIA.
  2. Do not change native semantics without a reason (no role="heading" on a button).
  3. Every interactive ARIA control must work with the keyboard.
  4. Never put aria-hidden="true" or role="presentation" on something focusable.
  5. Every interactive element needs an accessible name (visible text, aria-label, or aria-labelledby).

ARIA is the right tool when HTML has no equivalent: a disclosure that reports whether it is open, a live region that announces updates, a custom tab list or combo box.

The toggle button is announced as "Details, button, collapsed" and "expanded" after a click, because the script keeps aria-expanded in sync with the visible state. The icon button gets the name "Save note" from aria-label. The role="status" paragraph is a live region, so "Note saved" is announced without moving focus.

Wrong or stale ARIA is worse than none, so test with a screen reader or the browser's accessibility panel.

html
<button id="toggle" type="button" aria-expanded="false" aria-controls="details">Details</button>
<div id="details" hidden>Fees are payable in two instalments.</div>

<button id="save" type="button" aria-label="Save note">
  <svg width="16" height="16" aria-hidden="true"><rect width="16" height="16" fill="black"/></svg>
</button>

<p id="status" role="status"></p>
<script>
  const toggle = document.getElementById("toggle"), details = document.getElementById("details");
  toggle.addEventListener("click", () => {
    const open = toggle.getAttribute("aria-expanded") === "true";
    toggle.setAttribute("aria-expanded", String(!open));
    details.hidden = open;
  });
  document.getElementById("save").addEventListener("click", () => {
    document.getElementById("status").textContent = "Note saved";
  });
</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

  • Native HTML first: a button beats div role="button".
  • ARIA changes only what assistive technology hears, not behaviour or focus.
  • States like aria-expanded must be updated from script.
  • Never use aria-hidden on focusable content.
  • Every interactive element needs an accessible name.

Common mistakes

  • adding aria-label to a div or span with no role. Most screen readers ignore it, because the element has no semantic meaning to name.
  • setting aria-expanded in HTML and never updating it from JavaScript, so it reports the wrong state.

Follow-ups

  • what is the difference between aria-label, aria-labelledby and aria-describedby?
  • What is a live region and when would you use role="status"?
  • Why is aria-label on a plain div often useless?

Tips

  • Use the browser accessibility tree view in DevTools to see the computed role, name and state of an element.
  • Describe the disclosure button with aria-expanded as your example; it is short and complete.
  • Say that you test with the accessibility tree or a screen reader.
34.html-css-0034Mediummid

What are CSS floats, how do you clear them, and are they still used?

A float pushes an element to one side so inline content wraps around it. A parent does not grow to contain floats and later blocks can crowd beside them unless they use clear. display: flow-root on the parent contains floats cleanly. Floats are still right for wrapping text around an image but not for page layout.

Full answer

A float pushes an element to the left or right edge of its container. The element leaves normal flow in one way: surrounding inline content, such as text, wraps around it. Block boxes behind it still use the full width and sit underneath.

Floats were designed for putting an image inside a paragraph, like a photograph in a newspaper column. For years they were also used to build whole page layouts, which is why many old stylesheets are full of them.

Two side effects cause most bugs.

  • A parent does not grow to contain its floated children, so its height can collapse to zero.
  • A later element may be pulled up beside the float. clear: left, right or both on that element makes it move down below the float.

Today, display: flow-root on the parent contains floats cleanly, and Flexbox and Grid handle layout. Floats remain the right tool for wrapping text around an image. shape-outside can even make the text follow a curve.

In the first card the float is taller than the text, and since the card does not contain it, the card is only about as tall as the one line of text plus its padding and border. The second card uses flow-root and grows to hold the 120px photo, plus its margin, padding and border. In the third card, the paragraph wraps beside the photo, and the footer, which has clear: both, starts below it.

html
<style>
  body { margin: 0; font: 16px/1.5 sans-serif; width: 600px; }
  .card { border: 2px solid #333; padding: 8px; }
  .card.contained { display: flow-root; }
  .photo { float: left; width: 120px; height: 120px; margin: 0 12px 8px 0; background: #9cf; }
  .footer { clear: both; background: #eee; }
</style>
<div class="card" id="plain"><div class="photo"></div><p>Short note.</p></div>
<div class="card contained" id="fixed"><div class="photo"></div><p>Short note.</p></div>
<div class="card">
  <div class="photo" id="p3"></div>
  <p>Students of the evening batch can collect their identity cards from the front office between ten and four. Please carry the fee receipt with you.</p>
  <div class="footer" id="foot">Office hours</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

  • Float removes the element from normal flow but text wraps around it.
  • A parent with only floated children collapses unless it is a BFC.
  • clear: both on a later element moves it below the float.
  • display: flow-root contains floats without extra markup.
  • Use Flexbox or Grid for layout and float only for text wrapping.

Common mistakes

  • using clear on the float itself. Clear applies to the element that should move below the float.
  • adding an empty div with clear: both to contain floats. flow-root on the parent does the job without extra markup.

Follow-ups

  • what happens to display on a floated element?
  • What is a clearfix and why is it needed less today?
  • How does shape-outside change a float?

Tips

  • For modern layouts, reach for flex or grid first. Use float only when the content should wrap around something.
  • Describe the newspaper image use case; it frames floats as a tool with a purpose.
  • Give flow-root as the modern fix before the clearfix.
35.html-css-0035Mediummid

What is the difference between auto-fit and auto-fill in CSS Grid, and how does minmax() help?

repeat(auto-fill, minmax(150px, 1fr)) and repeat(auto-fit, ...) both create as many columns as fit. With few items, auto-fill keeps the empty columns, so items stay at the column width, while auto-fit collapses the empty columns and lets items stretch. minmax sets a minimum size and lets columns share the rest.

Full answer

repeat(auto-fill, ...) and repeat(auto-fit, ...) let the browser decide how many columns fit in the container. You give each column a minimum width with minmax(), and the browser creates as many columns as can fit.

The difference only appears when there are fewer items than columns that could fit.

  • auto-fill keeps all the columns it created, even the empty ones. Items stay at their column width and empty space remains on the right.
  • auto-fit creates the same columns, then collapses the empty ones to zero width. The remaining 1fr columns grow, so items stretch to fill the row.

In an 800px container, auto-fill creates five 160px columns (800 divided by 150 is 5.33, so five fit), and the three items each stay 160px wide. With auto-fit, the two empty columns collapse, and the three items stretch to about 267px each. When there are enough items to fill the row, both behave the same.

minmax(150px, 1fr) means "never narrower than 150px, otherwise share the space". On a screen narrower than 150px, a fixed 150px minimum would overflow. Writing minmax(min(100%, 150px), 1fr) caps the minimum at the container width.

No media queries are needed. The layout reflows from one column on a phone to many on a desktop. Rows are created automatically as needed and sized by grid-auto-rows, which is why they are called implicit tracks.

html
<style>
  body { margin: 0; width: 800px; font-family: sans-serif; }
  .grid { display: grid; gap: 0; margin-bottom: 16px; }
  .fill { grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); }
  .fit  { grid-template-columns: repeat(auto-fit,  minmax(150px, 1fr)); }
  .safe { grid-template-columns: repeat(auto-fit, minmax(min(100%, 150px), 1fr)); }
  .grid div { background: #cde; border: 1px solid #fff; padding: 8px; }
</style>
<div class="grid fill" id="fill"><div>1</div><div>2</div><div>3</div></div>
<div class="grid fit"  id="fit"><div>1</div><div>2</div><div>3</div></div>
<div class="grid safe" id="safe"><div>1</div><div>2</div><div>3</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

  • Both keywords create as many tracks as fit the container.
  • auto-fill keeps empty tracks; auto-fit collapses them.
  • The difference appears only when there are fewer items than columns that fit.
  • minmax(min(100%, 150px), 1fr) avoids overflow on narrow screens.
  • Extra rows are implicit tracks sized by grid-auto-rows.

Common mistakes

  • using auto-fit and auto-fill with fixed values only, such as repeat(auto-fit, 150px). Without 1fr in a minmax, the columns never grow.
  • forgetting that the minimum in minmax must fit on the smallest screen you support.

Follow-ups

  • what is the difference between explicit and implicit grid tracks?
  • What are implicit grid tracks?
  • How do you stop a grid item from overflowing with long text?

Tips

  • Use auto-fit for card grids where you want items to fill the row. Use auto-fill when you want a steady column width even if the last row is short.
  • Use numbers: three items in 800px with a 150px minimum give 160px tracks for fill and about 267px for fit.
  • Mention the min() trick for very small screens.
36.html-css-0036Mediummid

How do CSS keyframe animations differ from transitions, and how do you respect reduced-motion settings?

A transition animates between two states after a trigger, while a keyframe animation lists steps in @keyframes and can start itself, repeat and alternate. animation-fill-mode: forwards keeps the last frame. Respect prefers-reduced-motion by removing or shortening large movement, and give users a way to pause long-running motion.

Full answer

A transition animates between two states when something triggers a change, like hover. A keyframe animation is defined by a @keyframes block that lists steps, and it can start on its own, repeat, run back and forth, and pass through many steps.

An animation is controlled with these properties, usually in the animation shorthand:

  • animation-name: the @keyframes to use.
  • animation-duration, animation-timing-function, animation-delay.
  • animation-iteration-count: a number or infinite.
  • animation-direction: normal, reverse, alternate.
  • animation-fill-mode: whether the first or last frame styles apply before and after the run. forwards keeps the last frame, which is the usual fix for "the element jumps back at the end".
  • animation-play-state: running or paused.

Some users get headaches or dizziness from motion. Operating systems have a "reduce motion" setting, and CSS can read it with prefers-reduced-motion. Respect it by removing or shortening large movement, spinning and parallax.

The first box pulses forever. The second slides 100px and, because of forwards, stays there. Without forwards it would snap back to its start. With reduced motion switched on, the first box does not animate and the second jumps to the end almost instantly.

Animate transform and opacity where possible, since they avoid layout work. Never rely on animation alone to convey meaning, and give users a pause control for anything that moves for more than five seconds.

html
<style>
  @keyframes pulse { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.15); } }
  @keyframes slide { from { transform: translateX(0); } to { transform: translateX(100px); } }
  .pulse { width: 40px; height: 40px; background: tomato; animation: pulse 1.2s ease-in-out infinite; }
  .once  { width: 40px; height: 40px; background: teal; animation: slide 0.1s ease-out forwards; }
  @media (prefers-reduced-motion: reduce) {
    .pulse { animation: none; }
    .once  { animation-duration: 0.001s; }
  }
</style>
<div class="pulse" id="pulse"></div>
<div class="once" id="once"></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

  • Transitions need a trigger and two states; keyframes can run on their own.
  • Key properties: name, duration, timing function, delay, iteration count, direction, fill mode.
  • forwards keeps the end state after the animation finishes.
  • prefers-reduced-motion lets CSS respect the user's system setting.
  • Animate transform and opacity where possible.

Common mistakes

  • an infinite animation on a large area that cannot be stopped. It distracts users and can make some feel unwell.
  • forgetting animation-fill-mode: forwards and finding that the element resets to its first state after the animation ends.

Follow-ups

  • can you pause a CSS animation from JavaScript?
  • How do you pause a CSS animation from JavaScript?
  • What does animation-direction: alternate do?

Tips

  • Test reduced motion by turning it on in your operating system, or use the Rendering panel in DevTools to emulate it.
  • Mention reduced motion without being asked; it shows care for users.
  • Name one rule: pause control for anything moving more than five seconds.
37.html-css-0037Mediummid

What is margin collapsing, and when does it happen?

Margin collapsing merges touching vertical margins of block boxes into one: adjacent siblings, a parent and its first or last child with nothing between them, and empty blocks. Two positive margins give the larger, two negatives give the most negative, and mixed signs add. Flex and grid items, floats and absolutely positioned boxes do not collapse.

Full answer

Margin collapsing is a rule of block layout: when the vertical margins of two block boxes touch, they merge into one margin instead of adding. It confuses beginners because it only happens in the vertical direction, and only in some situations.

It happens when:

  • Adjacent siblings: the bottom margin of one block meets the top margin of the next.
  • Parent and first or last child, when nothing separates them (no border, padding, inline content or clear).
  • An empty block whose own top and bottom margins touch.

The merged size follows simple rules. Two positive margins give the larger one. Two negative margins give the one with the larger magnitude (the most negative). One positive and one negative are added together.

It does not happen between flex or grid items, for floated or absolutely positioned boxes, for inline-block boxes, or for the root element. A new block formatting context on the parent stops parent-child collapse.

In normal flow, the gap between the first two boxes is 30px (the larger of 30 and 20), not 50px. In the second pair, 30 and -10 combine to 20px. In the flex column, margins do not collapse, so the gap is 50px.

If you want predictable spacing, many teams avoid collapse on purpose. A common approach is to space siblings with one-direction margins only (top, or bottom, not both), or with gap in a flex or grid container.

html
<style>
  body { margin: 0; }
  .b { height: 20px; background: #9cf; }
  .m1 { margin-bottom: 30px; }
  .m2 { margin-top: 20px; }
  .neg { margin-top: -10px; }
  .flex { display: flex; flex-direction: column; }
  .flex .m1 { margin-bottom: 30px; }
  .flex .m2 { margin-top: 20px; }
</style>
<div id="blockwrap">
  <div class="b m1" id="a1"></div>
  <div class="b m2" id="a2"></div>
</div>
<div id="negwrap">
  <div class="b m1" id="n1"></div>
  <div class="b neg" id="n2"></div>
</div>
<div class="flex" id="flexwrap">
  <div class="b m1" id="f1"></div>
  <div class="b m2" id="f2"></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

  • Only vertical margins collapse; horizontal margins add.
  • Cases: adjacent siblings, parent and child, and empty blocks.
  • Positive pairs give the larger; negative pairs the most negative; mixed signs are added.
  • Flex and grid items, floats and absolute boxes do not collapse.
  • Padding, border or a new BFC stops parent and child collapse.

Common mistakes

  • adding margin-top to the first child inside a parent and seeing the whole parent move down instead. The child margin collapsed through the parent.
  • believing horizontal margins collapse too. Left and right margins always add up.

Follow-ups

  • how can you stop a child margin escaping its parent?
  • Why does a child's margin-top move the whole parent?
  • Does gap in flex or grid collapse with margins?

Tips

  • Choose one direction for vertical spacing in components, for example margin-bottom only. Then collapse rarely matters.
  • Give the 30 and 20 example and say the gap is 30. Numbers make it stick.
  • Mention that using margin in one direction avoids most surprises.
38.html-css-0038Mediummid

Why does a flex item with long text overflow its container, and how do you fix it?

A flex item has min-width: auto, so it will not shrink below its content width. Long unbroken text or white-space: nowrap makes it overflow the container. Fix it with min-width: 0 (or overflow other than visible) and then add overflow: hidden and text-overflow: ellipsis. In grid, use minmax(0, 1fr) for the same reason.

Full answer

A flex item has min-width: auto by default. For most items that means "never shrink below the width of its content". If the content is a long unbroken string or text with white-space: nowrap, the item refuses to shrink, and it pushes the row wider than its container.

The fix is to allow the item to shrink with min-width: 0 (or any overflow value other than visible, which changes the automatic minimum to zero). Then add the overflow behaviour you want, such as an ellipsis.

In the first row, the title stays as wide as its text and pushes the Open button out of the row. In the second row, the title shrinks to 240px (the 300px of room inside the row minus the 60px button), the text is cut with an ellipsis, and the button stays inside.

The same problem happens vertically in column layouts (min-height: auto) and with grid items. In a grid, the equivalent fix is minmax(0, 1fr) instead of plain 1fr, because 1fr means minmax(auto, 1fr).

When you meet an unexpected overflow in flex or grid, open DevTools, select the item and check its computed width against its content. This bug is behind many reports that a layout breaks when a name or title is long.

html
<style>
  body { margin: 0; font: 16px sans-serif; }
  .row { display: flex; width: 300px; margin-bottom: 12px; border: 1px solid #999; }
  .title { flex: 1; white-space: nowrap; background: #eef; }
  .row.fixed .title { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
  .action { flex: 0 0 60px; background: #fe9; }
</style>
<div class="row" id="broken">
  <div class="title" id="t1">Introduction_to_Data_Structures_and_Algorithms_Lecture_Notes.pdf</div>
  <button class="action" id="a1">Open</button>
</div>
<div class="row fixed" id="fixed">
  <div class="title" id="t2">Introduction_to_Data_Structures_and_Algorithms_Lecture_Notes.pdf</div>
  <button class="action" id="a2">Open</button>
</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

  • Flex items default to min-width: auto and refuse to shrink below content.
  • min-width: 0 allows the item to shrink.
  • Ellipsis needs overflow: hidden, white-space: nowrap and text-overflow: ellipsis.
  • The same cause applies to min-height in column layouts.
  • In grid, plain 1fr has an automatic minimum; use minmax(0, 1fr).

Common mistakes

  • adding overflow: hidden to the container and not the item. The container hides the overflow but the item layout is still wrong.
  • using fixed pixel widths on items to avoid the problem. They break again at another screen size.

Follow-ups

  • how is the same bug fixed in Grid?
  • Why does 1fr in grid sometimes overflow?
  • What other property can change the automatic minimum size of a flex item?

Tips

  • For ellipsis, remember the trio: overflow: hidden, white-space: nowrap and text-overflow: ellipsis, plus min-width: 0 on a flex item.
  • Say the cause (min-width: auto) before the fix. Many answers give only the fix.
  • Mention checking computed widths in DevTools when you find unexpected overflow.
39.html-css-0039Mediummid

How does keyboard focus work, and when should you use :focus-visible, tabindex and a skip link?

Keyboard users move through focusable elements in DOM order. tabindex="0" adds an element to the tab order, -1 makes it focusable by script only, and positive values should be avoided. :focus-visible shows a focus ring mainly for keyboard focus. A skip link lets users bypass repeated navigation, and removing outlines without a replacement makes pages unusable.

Full answer

Keyboard users move through a page with Tab and Shift+Tab. The browser visits focusable elements in the order they appear in the DOM: links with href, buttons, form controls, and anything with a tabindex. The focus ring shows where they are. Removing it with outline: none and giving nothing back makes the page unusable for them.

tabindex has three useful meanings:

  • tabindex="0": add a normally non-focusable element to the tab order, in DOM order.
  • tabindex="-1": focusable by script (element.focus()) or a link, but not in the Tab sequence. Good for the target of a skip link or for moving focus to a heading.
  • A positive number: forces a custom order. Avoid it, because it breaks the natural order and is hard to maintain.

:focus matches any focused element, including after a mouse click on a button. :focus-visible matches only when the browser decides a visible indicator is useful, which is usually for keyboard focus and text inputs. It lets you keep a clear ring for keyboard users without showing it on every mouse click.

A skip link is the first link on the page. It lets keyboard users jump past a long navigation to the main content.

Pressing Tab once focuses the skip link and shows it. Another Tab visits the nav links in order. Clicking the button with the mouse focuses it, but :focus-visible does not match, so no ring appears. Pressing Tab to reach it from the keyboard matches :focus-visible, so the blue ring shows.

When you open a modal or change the page content from script, move focus yourself with focus(), and return it to the control that opened the modal when it closes.

html
<style>
  .skip { position: absolute; left: -999px; }
  .skip:focus { left: 8px; top: 8px; background: gold; padding: 8px; }
  button, a { outline-offset: 2px; }
  button:focus-visible, a:focus-visible { outline: 3px solid #0a6cff; }
  button:focus:not(:focus-visible) { outline: none; }
</style>
<a class="skip" href="#main" id="skip">Skip to main content</a>
<nav><a href="#a" id="n1">Home</a> <a href="#b" id="n2">Courses</a></nav>
<button id="btn" type="button">Enrol</button>
<main id="main" tabindex="-1"><h1>Main content</h1></main>

Checked with real Tab key presses and a mouse click on the button. 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

  • Tab order follows DOM order for links, buttons, controls and tabindex=0 elements.
  • tabindex=-1 allows script focus, such as moving focus to a heading.
  • Avoid positive tabindex values.
  • :focus-visible keeps a clear ring for keyboard users without noise on mouse clicks.
  • Never use outline: none without a visible replacement.

Common mistakes

  • outline: none on buttons and links with no replacement style. Keyboard users cannot see where they are.
  • making a div clickable with tabindex="0" and an onclick handler only. It then needs Enter and Space key handling and a role, so use a button instead.

Follow-ups

  • why avoid positive tabindex values?
  • How would you move focus after loading new content?
  • What does a skip link do and where should it be placed?

Tips

  • Tab through every page you build. If you lose track of where you are, or cannot reach or activate something, fix it before shipping.
  • Say that you tab through every page you build. It is a real habit interviewers want to hear.
  • Mention returning focus to the opener when a dialog closes.
40.html-css-0040Mediummid

What are CSS logical properties, and why are they useful for international sites?

Logical properties describe sides relative to text direction and writing mode, such as margin-inline-start and padding-block, instead of left and top. One stylesheet then works for left-to-right, right-to-left and vertical scripts. inset, inline-size and block-size follow the same idea.

Full answer

Physical properties name a screen side: margin-left, padding-right, border-top, width. Logical properties name a side relative to the text direction and writing mode: margin-inline-start, padding-inline-end, border-block-start, inline-size.

In a left-to-right language like English, "inline start" is the left. In a right-to-left language like Arabic or Hebrew, it is the right. In vertical writing modes the block and inline axes also turn. When you write layout in logical terms, one stylesheet works for all of them, with no separate right-to-left overrides.

The mapping:

  • inline is the direction text runs. block is the direction blocks stack.
  • margin-inline-start replaces margin-left in left-to-right text.
  • padding-block sets both top and bottom in horizontal writing.
  • inset-inline-start replaces left for positioned elements. inset: 0 is the shorthand for all four sides.
  • text-align: start and end replace left and right.
  • inline-size and block-size replace width and height in horizontal text.
  • border-start-start-radius and its siblings round corners logically.

In the left-to-right block, the note has a 24px margin on its left and a teal bar on its left, and the badge is in the top right corner. In the dir="rtl" block, the same CSS gives a 24px margin on the right, the bar on the right, and the badge in the top left corner.

Logical properties are not a replacement for every physical one. A drop shadow that must fall towards the bottom right regardless of language, or a graphic that is tied to a specific side, can stay physical. Check current support tables if you target very old browsers.

html
<style>
  .note {
    margin-inline-start: 24px;
    padding-inline: 12px;
    border-inline-start: 4px solid teal;
    text-align: start;
  }
  .badge { position: absolute; inset-block-start: 0; inset-inline-end: 0; }
  .wrap { position: relative; width: 300px; }
</style>
<div class="wrap" id="ltr"><p class="note" id="p1">Fees are due on the first of each month.</p><span class="badge" id="b1">New</span></div>
<div class="wrap" dir="rtl" id="rtl"><p class="note" id="p2">الرسوم مستحقة في أول كل شهر</p><span class="badge" id="b2">New</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

  • inline is the text direction axis; block is the stacking direction.
  • margin-inline-start replaces margin-left in left-to-right text and flips in right-to-left.
  • inset-inline-end, text-align: start and inline-size are logical equivalents.
  • Direction comes from dir or writing-mode.
  • Some physical properties, like a shadow direction, can stay physical.

Common mistakes

  • mixing margin-left in one place and margin-inline-start in another for the same layout, then wondering why right-to-left breaks.
  • forgetting the dir attribute or lang on the html element. Direction comes from dir (or the writing mode in CSS), not from the language alone.

Follow-ups

  • what does inline-size mean in a vertical writing mode?
  • What is the logical equivalent of width in a vertical writing mode?
  • How does text-align: start differ from left?

Tips

  • When starting a new project, write margins, paddings and positions logically from day one. It costs nothing and saves a rewrite when the site gets a right-to-left language.
  • Give the right-to-left example: the same CSS puts the margin on the right. It is the point of the feature.
  • Say you write new code logically by default.