Questions 101–120 of 193 · 0 of 20 on this page marked learned
101.html-css-0101Hardsenior
Why can 100vh cause problems on phones, and what are svh, lvh and dvh?
Mobile browser toolbars move, so 100vh can be taller than the visible area. lvh is the large viewport, svh the small and dvh the dynamic one that follows the toolbars. Use svh for a safe fit, dvh for an exact fit, and write the old vh line first as a fallback.
Full answer
On many phones the browser toolbar and address bar slide away when the user scrolls down, and return when they scroll up. The visible area of the page grows and shrinks. The classic vh unit was defined as a fixed size, as if the toolbars were hidden. So 100vh can be taller than the visible area when the toolbar is shown, and a bottom button or footer sized with it goes below the visible edge.
Newer viewport units cover the cases:
lvh is the large viewport: the size when the toolbars are retracted. Plain vh matches this.
svh is the small viewport: the size when the toolbars are fully shown. It is always fully visible.
dvh is the dynamic viewport: it follows the real visible size and changes as the toolbars move.
There are matching width and logical units (dvw, dvi, dvb and so on), though height is where the problem is.
How to choose:
A full-screen hero or a modal sheet that must always fit on screen: use svh for a safe size, or dvh for an exact fit.
A layout that should fill the screen but where a small change is acceptable: dvh. Note that it can cause layout changes while scrolling, so avoid it for large areas that cause reflow on every scroll.
When the toolbar behaviour does not matter: vh is fine.
Unsupported browsers ignore a declaration with an unknown unit, so write the old value first, then the new one. Also check the support table. On desktop, all three equal the window height, because there is no sliding toolbar.
On a desktop browser, the hero is exactly as tall as the window, because small, large and dynamic sizes are the same there. On a phone, the hero is as tall as the area visible when the address bar is shown, and the sheet follows the visible size as the toolbar moves.
The phone behaviour is not shown by this example. Test it on real devices or in a device emulator with the browser toolbar visible.
Checked on a desktop viewport, where the three units give the same height. The sliding toolbar on phones was not tested. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
vh behaves like the large viewport on many phones.
svh is the smallest visible height; lvh is the largest.
dvh follows the visible height as toolbars move.
On desktop all three are equal.
Write a vh fallback before the newer unit.
Common mistakes
Using 100vh for a full-screen mobile layout and finding the bottom button hidden under the toolbar.
Using dvh for large areas that must not resize while the user scrolls.
Using the new units with no fallback line for older browsers.
Follow-ups
Which unit is the same as the old vh?
Why write the 100vh line before the 100svh line?
Tips
Define the three units in one line each: large, small, dynamic.
Say that on desktop they are equal, and the difference only appears on mobile browsers with moving toolbars.
102.html-css-0102Hardsenior
How do you fade a popover or dialog in and out with CSS only, even though display and overlay change?
@starting-style gives the first-frame style so an entry transition can run, and transition-behavior: allow-discrete lets display and overlay switch at the end of the exit transition. Together they allow CSS-only fades for popovers and dialogs. They are newer, so check support and accept an instant fallback.
Full answer
Two things make entry and exit animations hard.
When an element goes from display: none to shown, it has no earlier style, so a transition has nothing to start from. It just appears.
When it goes back to display: none, the element disappears at once, so an exit transition never plays.
Newer CSS has features for both.
@starting-style defines the style an element has on its first frame, before the first style update. Put opacity: 0 there, and the transition runs from 0 to the normal value when the element is first shown.
transition-behavior: allow-discrete lets properties that cannot be calculated in between, such as display and overlay, take part in transitions. With it, display flips at the end of the exit transition, not at the start, so the fade-out is visible. overlay does the same for the top layer, which keeps a popover or dialog on screen until the transition ends. A shorthand transition: opacity 0.3s, display 0.3s allow-discrete, overlay 0.3s allow-discrete covers all three.
For a popover, the rules are applied to :popover-open for the open state, the base rule for the closed state, and @starting-style for the first frame.
These are newer features. Check the support table. Without support, the popover still opens and closes, only without animation. That is a good fallback because the content and behaviour stay the same.
Also respect reduced motion: a short fade is usually fine, but remove movement and long durations for people who ask for less motion.
On click, the popover fades from invisible to visible over 0.4 seconds. When it is closed, it fades out first and is then removed, so the exit is visible. If the browser does not support the features, it simply appears and disappears.
The check for this example was done in one browser only, so read the support table before shipping.
Checked in Chrome 156 only, by reading the opacity and display values during the open and close transitions. 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
Entering from display: none has no start style without @starting-style.
Leaving display: none cuts the exit unless allow-discrete is used.
overlay keeps top layer elements visible until the end of the transition.
The fallback is an instant show and hide.
Add a reduced motion rule.
Common mistakes
Expecting a transition to play when going from display: none, with no @starting-style.
Forgetting allow-discrete for display, so the element vanishes before the fade-out plays.
Not adding a reduced motion rule.
Follow-ups
Why is overlay in the transition list for a popover or dialog?
What is the fallback in a browser without these features?
Tips
Explain the two problems: no starting style on entry, and display: none cuts the exit.
Name the two tools: @starting-style and transition-behavior: allow-discrete.
103.html-css-0103Hardsenior
A CSS rule has no effect on the page. Walk through how you find out why, using a real example.
Inspect the element, check that the rule is listed, then see whether it is struck out (lost the cascade) or has a warning icon (invalid). Check the computed value, then specificity, layers and source order. Fix the cause: typos, invalid values, missing semicolons or an overly specific selector.
Full answer
When a rule seems ignored, do not edit blindly. Follow the same steps each time.
Inspect the element in DevTools. Check that the element is the one you think it is, and that the rule appears in the Styles pane. If the rule is not listed, the selector did not match or the file did not load. Check the Network panel and the selector spelling.
Look at how the rule is shown. A line with a strike-through lost to another rule, which is shown above it. A warning icon beside a declaration means the property name or value is invalid, and the browser dropped it.
Check the Computed pane for the final value, and expand it to see which rule won.
Think about the cascade in order: origin and !important, then layers, then specificity, then source order.
Look for typos, missing semicolons, wrong units and a missing closing brace.
Check inherited and parent effects: the property may not apply to that element type, or a parent may hide or clip it.
Here is a small page with four bugs. Each one has a different cause.
What happens and why:
The title stays black, because colour is not a property. The browser ignores the declaration.
The note keeps the default size, because 1,2rem is not a valid length. The decimal separator must be a dot.
The link is gray, not blue. The selector #side a has an id and wins on specificity over .link, even though .link is later.
The tag has no colour and no background. A missing semicolon makes crimson background: yellow one invalid value, and the whole declaration is dropped, including the colour.
For the link, the better long-term fix is to lower the specificity of #side a to a class, and not to raise .link with more ids. Avoid !important unless you have no other way.
After the fix, reload without cache and recheck the Computed pane.
The page was run twice, once with the bugs and once fixed, and the computed values were read from both. 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
Find out whether the selector matches and the file loads.
A strike-through means the rule lost; a warning icon means it was invalid.
The cascade order is importance, layers, specificity, source order.
Typos, bad units and missing semicolons are common causes.
Avoid !important as a first fix.
Common mistakes
Adding !important to every rule that seems ignored, which makes the cascade harder to manage.
Not looking for the invalid-declaration warning in the Styles pane.
Changing the selector many times without checking whether it matches the element.
Follow-ups
How do you tell an invalid declaration from one that lost the cascade?
Why is !important a poor first fix?
Tips
Give a repeatable order of checks, not a guess.
Name DevTools features: strike-through, warning icon and the Computed pane.
104.html-css-0104Easyfresher
How do input types and the inputmode attribute improve a form, and what do they not do?
The type attribute tells the browser what to expect, so it can show a suitable keyboard or picker and run basic checks. inputmode changes only the keyboard. These are conveniences, not security, so the server must check again.
Full answer
The type attribute of an input tells the browser what kind of value to expect. The browser can then show a better keyboard on phones, offer a date picker, and run basic checks.
email shows a keyboard with the @ sign and checks that the value looks like an address.
tel shows a number pad. It does not check the format, because phone numbers differ by country.
url checks for a valid address with a scheme.
number allows digits only, gives spinner arrows, and works with min, max and step. It is a poor choice for codes such as a postal code or a card number, because it removes leading zeros and shows arrows that make no sense.
date, time and datetime-local show a picker. The value is always in a fixed format such as 2026-12-04, whatever the display.
search is a text box with a clear button in some browsers. password hides the characters.
inputmode changes only the keyboard and not the checks. For a postal code or a one-time code, use type="text" with inputmode="numeric". The pattern attribute then checks the format.
Types are a help and not security. Users can type anything into a plain text field, and a script can send anything to the server, so the server must check every value again.
If a script sets the email field to abc, its validity reports a type mismatch. The number field rejects letters and keeps an empty value. The postal code field keeps its leading zeros as text, and its pattern rejects the value 123.
The keyboards themselves depend on the phone, so check them on a real device.
The check set values by script and read the validity state. The phone keyboards were not tested. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
type picks the keyboard, picker and basic checks.
Do not use number for codes that keep leading zeros.
inputmode changes the keyboard without adding checks.
pattern and the server do the real checking.
Test keyboards on real phones.
Common mistakes
Using type="number" for postal codes, phone numbers or card numbers.
Assuming type="email" makes a value safe or real. It only checks the shape.
Skipping server-side checks because the browser already checked.
Follow-ups
What does the step attribute do on a number input?
Why does a date input send a fixed format?
Tips
Give one example where the type is wrong, such as a postal code as a number.
Say that inputmode changes the keyboard only.
105.html-css-0105Mediummid
What are autocomplete tokens, and why should a sign-up or checkout form use them?
autocomplete tokens say what each field means, so browsers and password managers can fill it correctly. Use specific tokens such as given-name, email, new-password and one-time-code, add a section for shipping and billing, and avoid off for ordinary fields.
Full answer
The autocomplete attribute tells the browser, a password manager or an assistive tool what each field is for. With the right token, the browser can fill a name, address or code in one step. This saves time, reduces mistakes and helps people with motor or memory difficulties. It is also part of accessibility rules, which ask that fields about the user can be filled automatically.
Accounts: username, current-password for sign-in and new-password for sign-up or a password change. These help password managers choose to fill or to suggest a strong password.
one-time-code lets a phone offer the code from a text message.
Tokens can have a section or purpose in front, such as shipping postal-code and billing postal-code, to separate two groups of address fields on one page. off asks the browser not to fill, but browsers may ignore it for login fields, and it can harm users, so use it only for fields such as a search box for a one-time value.
Tokens work together with a good name and a connected label. A visible label is still needed.
Each field has a token that matches its meaning, and each has a label connected with for. The check reads the attributes, because browser autofill needs saved data and a real profile.
Test with a real browser profile and a password manager, since the fill behaviour belongs to the browser.
The check read the attributes and the label links. Browser autofill needs a saved profile and was not tested. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
Tokens describe the meaning of a field.
Use current-password and new-password for accounts.
one-time-code helps with SMS codes.
Prefix shipping or billing to separate groups.
Keep real labels. Test with a real profile.
Common mistakes
Setting autocomplete="off" on login and checkout fields, which breaks password managers.
Using the same token for shipping and billing fields on one page with no section prefix.
Using a placeholder or a made-up name instead of a visible label and a correct token.
Follow-ups
How do you separate shipping and billing fields on one page?
When is autocomplete="off" reasonable?
Tips
Link tokens to accessibility and to fewer typing errors.
Name new-password and one-time-code. They are the ones people forget.
106.html-css-0106Mediummid
How does a file input work, and how do you read the chosen files in the browser?
A file input gives a FileList of File objects after the user chooses, and the change event tells you. accept is only a hint for the picker, so check type and size in script and on the server. Forms that upload files need method post and enctype multipart/form-data.
Full answer
A file input is <input type="file">. Useful attributes:
accept suggests which files the picker shows, for example accept="image/png, image/jpeg" or accept=".pdf". It is a hint for the picker only. A user can still choose another kind of file, so check the type and size in a script and on the server.
multiple allows more than one file.
capture asks a phone to use the camera for some types. Support differs, so test it.
webkitdirectory lets a user pick a folder in browsers that support it.
After the user picks files, the input's files property is a FileList. Each item is a File with name, size, type and lastModified. The change event fires when the choice changes. A file can be read in the page with await file.text() or file.arrayBuffer(). To show a preview of an image, use URL.createObjectURL(file) and revoke the address when done.
A form that sends files must use method="post" and enctype="multipart/form-data". Without that encoding, only the file names are sent.
For a nicer look, the native control is hard to style. A common safe pattern is a label styled as a button that is connected to a visually hidden input. Keep the input focusable so the keyboard still works.
The script lists the number of files, counts the ones over 1000 bytes and reads the first one as text. A real page should show a message in an element for screen readers and handle large files with care.
The native picker window cannot be driven by this check, so the example sets files through a script instead.
The check set the files by script, because the native file picker window cannot be driven here. 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
files is a FileList of File objects with name, size and type.
accept and capture are hints, not rules.
multiple allows several files.
Use multipart/form-data to send file contents.
Keep a visually hidden input focusable if you restyle it.
Common mistakes
Trusting accept to block other file types.
Forgetting enctype="multipart/form-data", so the server gets file names and not file contents.
Hiding the input with display: none so keyboard users cannot reach it.
Follow-ups
How do you show an image preview before upload?
What is the difference between accept and a size check?
Tips
Say that accept is a hint, and the server must check.
Mention enctype. It is a classic bug.
107.html-css-0107Mediummid
When would you use select, datalist or radio buttons for a choice, and how do their values behave?
Use radio buttons for a few options, select for a longer fixed list, and datalist for suggestions in a text input. A select value must be one of its options, while a datalist input accepts any text. Add an empty first option and a label.
Full answer
Pick the control by how many choices there are and whether free text is allowed.
Radio buttons suit a small set of options, about two to five, where seeing all of them helps. The user picks exactly one.
select suits a longer fixed list, such as a country. The value must be one of the options. optgroup groups the options under a label, and multiple allows several picks, although a list of checkboxes is often easier to use.
datalist works with a text input through its list attribute. It suggests values while the user types, but the user can still type anything. Use it for suggestions, for example a city field, and do not use it when the value must come from the list.
Points that matter:
A select has a first option with an empty value such as "Choose a country" when the field is required, so the user must make a choice.
option text is what the user sees. The value attribute is what is sent. If value is missing, the text is sent.
datalist options do not make a field valid or invalid. Add pattern or script checks if the value must match.
select is styled by the browser. appearance and a custom arrow can change the look, but the popup list stays mostly native, and that is a good thing for keyboard and screen reader users.
Setting the select to a value that is not in the list leaves it empty, and the required check fails. The city field keeps any text, even "Zulu", because the list only suggests.
Always add a label, because the options do not name the field.
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
Radio for a few options, select for a long fixed list.
datalist suggests but does not limit.
optgroup groups options under a label.
An empty first option makes required useful.
Always connect a label.
Common mistakes
Using datalist when the value must be one of the options. It never enforces that.
Forgetting the empty first option on a required select, so the first real option looks pre-chosen.
Using a native select with hundreds of options when a search box would be faster.
Follow-ups
How does a select send its value?
When is a list of checkboxes better than select multiple?
Tips
Choose by size of list and whether free text is allowed.
State that datalist only suggests.
108.html-css-0108Hardsenior
A field is missing from the data the server receives. Which causes would you check in the form?
A control is sent only with a name, when it is not disabled, when it belongs to the form, and, for checkboxes and radios, when it is checked. Print new FormData(form) to see what will be sent. Use readonly when the value must be sent but not edited.
Full answer
When a field is missing, the cause is almost always in the markup. The browser follows fixed rules about which controls are sent.
A control is sent only if all of these are true:
It has a name attribute. An id alone is not enough.
It is not disabled. A disabled control is skipped. A readonly control is still sent, so use readonly when the user must not edit a value but the server needs it.
It belongs to the form. It must be inside the form, or point to it with the form attribute.
For checkboxes and radio buttons, it must be checked. An unchecked checkbox sends nothing, not even false. The server must treat a missing key as off.
For a select, an option must be selected. For a button, only the button used to submit is sent, with its name and value.
For file inputs, the form needs the multipart encoding to send the file itself.
Other causes: two controls with the same name make a list of values and not one value, a control created after submit is too late, and a fieldset disabled disables every control inside it.
A fast way to see what will be sent is new FormData(form). Print its entries in the console before blaming the server.
Reading Object.fromEntries(new FormData(f)) gives a, d, g and i. The field with only an id, the disabled field, the unchecked box and the field inside the disabled fieldset are missing. The field outside the form is present because it uses the form attribute.
When the data is fine in the browser, look at the encoding of the request and at the server code.
Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
A control without a name is not sent.
Disabled controls are skipped; readonly ones are sent.
Unchecked checkboxes and radios send nothing.
The form attribute can attach a control from outside.
Inspect FormData before blaming the server.
Common mistakes
Giving a field an id but no name.
Using disabled for a value that the server still needs. Use readonly, or a hidden input.
Expecting an unchecked checkbox to send false.
Follow-ups
What is the difference between readonly and disabled?
How would you send a value for an unchecked checkbox?
Tips
List the rules as a checklist: name, not disabled, in the form, checked.
Show FormData as the debug tool, so you test before guessing.
109.html-css-0109Easyfresher
A button inside a form reloads the page when clicked, although it should only run a script. What is wrong?
A button in a form has type submit by default, so a click submits the form and reloads the page. Set type="button" for script-only buttons, or handle the form's submit event and call preventDefault.
Full answer
A button inside a form has the type submit when no type is given. Clicking it submits the form, and the browser loads the form's address, which often reloads the same page. This is not a bug in the script. It is the default behaviour of the element.
There are two fixes, and both are good.
Give the button the right type. Use type="button" for a button that only runs a script. Use type="submit" when it should submit. Writing the type on every button is a good habit.
Handle the submit event and call event.preventDefault(). This is the right way when you want to send the data with fetch and stay on the page. Listen to submit on the form, not click on the button, because a form can also be submitted with the Enter key.
Related points:
type="reset" clears the form and is rarely wanted.
A button outside any form does nothing special by default.
The form attribute on a button can attach it to a form somewhere else on the page.
A link styled as a button does not submit anything. Use a real button for actions.
Clicking the first button counts as a submit, because its default type is submit. Clicking the second button does not. Clicking the third button counts as a submit. Because the handler calls preventDefault, the page stays in place and the script can send the data.
If the page still reloads after this, check for an error in the handler, since an error before preventDefault lets the submit go on.
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
The default button type inside a form is submit.
Use type="button" for buttons that only run scripts.
Handle the submit event on the form, not the click.
preventDefault stops the page from loading.
Write the type on every button.
Common mistakes
Leaving out type on buttons inside forms.
Listening to click on the submit button, which misses submits made with the Enter key.
Calling preventDefault after code that can throw an error.
Follow-ups
Why listen to submit instead of click?
What does a button do outside a form?
Tips
Say the default type is submit, and explain it in one line.
Prefer the submit event on the form over a click on the button.
110.html-css-0110Mediummid
Why is :invalid a poor way to show form errors, and what does :user-invalid do better?
:invalid matches as soon as a value breaks a rule, even before the user has typed. :user-invalid matches only after interaction, so error styles appear at a better time. It is newer, so provide a fallback, and always add error text linked with aria-describedby.
Full answer
:invalid matches any control whose value breaks its rules, and this is true from the moment the page loads. An empty required field matches :invalid before the user has typed anything. If you style :invalid with a red border, the whole form is red on the first view. That is unfriendly.
:user-invalid matches only after the user has interacted with the control. In practice that means after the field lost focus or after the user tried to submit. Then the error style shows at a time when it helps. :user-valid is the matching state for correct values.
Older ways to get the same result:
A class added by a script on the blur event.
The :placeholder-shown trick, which only works for empty fields and needs a placeholder.
:focus:invalid to show the error only while the user is typing.
:user-invalid is newer. Check the support table. A fallback is a script that adds a class after blur. Because an unsupported selector makes a whole rule invalid, write the :user-invalid rule on its own.
Colour alone is not enough for an error. Add text, and connect it to the field with aria-describedby. The message should say what to do, such as "Enter a valid email address".
On load the field matches :invalid but not :user-invalid, so it is plain. After the user types abc and leaves the field, it gets the red border and the message appears.
The check types real key presses, because a script that sets the value does not count as user interaction.
The check typed real key presses and moved focus away, because a script that sets the value does not count as user interaction. 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
:invalid matches from page load.
:user-invalid waits until the user has interacted.
Fallback: add a class on blur with a script.
Add text and aria-describedby, not colour only.
Keep the :user-invalid rule separate for support reasons.
Common mistakes
Styling :invalid directly, so the form shows errors before the user has typed.
Showing the error only with a red colour and no text.
Putting :user-invalid in the same selector list as older selectors, which can invalidate the whole rule in browsers that do not know it.
Follow-ups
How would you show errors in a browser that lacks :user-invalid?
Why does a script that sets value not trigger :user-invalid?
Tips
Say when each one starts to match: on load or after interaction.
Mention the fallback script, and the need for text and aria-describedby.
111.html-css-0111Easyfresher
Why are tables a poor tool for page layout, and what do you use instead?
A table tells assistive tools that content is data in rows and columns, so using it for layout adds noise, ties the order to the visuals and makes responsive changes hard. Use Flexbox or Grid for layout, and keep tables for real data.
Full answer
Years ago, pages were laid out with tables, because it was the only way to make columns. Today that is considered a mistake, for clear reasons.
Meaning: a table says that the content is data in rows and columns. Screen readers announce the number of rows and columns and let users move cell by cell. For a layout, that is noise, and the reading order may not match the visual order.
Flexibility: a table layout is rigid. Cells grow with their content in both directions. It is hard to change the layout for a phone without changing the HTML.
Weight and maintenance: layout tables need many nested elements, and the markup mixes structure with looks.
Search and tools: the content is harder to reuse, to print and to test.
The right tools are CSS Flexbox for one-dimensional rows or columns and CSS Grid for two-dimensional layouts. Both keep the HTML meaningful and let a media query change the layout.
When is a table right? When the content is truly tabular: a timetable, a price list, a score board. Use caption, th with scope and a clear structure. If an old email template forces a layout table, add role="presentation" so assistive tools ignore the table structure. HTML emails are one of the few places where this is still needed, because many email clients have weak CSS support.
Both versions show a menu on the left and content on the right. The table needs a role to hide its table meaning, while the grid uses real nav and main elements that carry the right meaning without extra work. At a narrow width, the grid can change to one column with a media query, and the table cannot.
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 carry data meaning that layouts do not need.
Table layouts are rigid and hard to make responsive.
Use Flexbox for one dimension and Grid for two.
Real data should still use a table with caption and th.
Email templates may still need layout tables.
Common mistakes
Using a table for layout and adding spacer cells to move things around.
Using display: table styles on divs without thinking about the reason. Flexbox or Grid is usually simpler.
Removing table semantics from a real data table.
Follow-ups
What does role="presentation" do on a table?
How would you make a two-column layout stack on a phone?
Tips
Say that tables mean data, and layout needs different tools.
Mention HTML email as the honest exception.
112.html-css-0112Mediummid
What is the template element, and how do you use it to build repeated markup?
A template holds inert HTML in a DocumentFragment: nothing renders, runs or loads. Clone template.content with cloneNode(true), fill it using textContent and add it to the page. It is cleaner and safer than gluing HTML strings.
Full answer
A template element holds HTML that is not shown and not run. Its content is parsed but kept inert in a separate document fragment. Images inside do not load, scripts inside do not run, and styles inside do not apply to the page. A normal querySelector on the page does not find elements inside it.
To use it, read template.content, which is a DocumentFragment. Call content.cloneNode(true) to make a copy, fill the copy with data and add it to the page. Each clone is independent, so you can repeat it for every row of data.
Why not build strings with innerHTML?
A template is real HTML, so it is easy to read and edit, and editors can check it.
Setting textContent on parts of the clone puts user text in as plain text and avoids script injection problems that happen when you glue user input into an HTML string.
It is faster than parsing the same long string again for each item.
Compared with a div that is hidden with CSS, a template's content is never rendered and never fetches images.
Templates are also the basis of custom elements with shadow DOM, where a template is cloned into the shadow root.
The page shows two list items with the names. Searching the page for .item finds only the two clones, and not the template's own list item. The image in the template is never requested until a clone is added, and the clone then requests it.
Always set text with textContent, and not with an HTML string, when the data comes from users.
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
Template content is inert and not part of the page tree.
Use content.cloneNode(true) to make copies.
Fill clones with textContent for safety.
Each clone is independent.
Templates are used by custom elements.
Common mistakes
Looking for elements inside a template with document.querySelector.
Forgetting cloneNode(true), which moves the content instead of copying it.
Filling clones with innerHTML and user text.
Follow-ups
Why does an image in a template not load?
What does cloneNode(true) do differently from cloneNode(false)?
Tips
Explain inert content and the DocumentFragment in one sentence.
Mention textContent as the safe way to insert text.
113.html-css-0113Hardsenior
How do you define a custom element, and when do its lifecycle callbacks run?
Extend HTMLElement and register the class with customElements.define using a name with a dash. The browser calls constructor, connectedCallback, disconnectedCallback and attributeChangedCallback for observed attributes. Keep the constructor light, set up in connectedCallback and clean up in disconnectedCallback.
Full answer
A custom element is your own HTML tag backed by a JavaScript class. The class extends HTMLElement, and you register it with customElements.define("name-here", Class). The name must contain a dash, such as course-badge, so it cannot clash with future built-in tags.
The browser calls these methods:
constructor: when an element is created. Call super() first. Do not read attributes or add children here, because an element made by the parser may not have them yet. Keep it light.
connectedCallback: each time the element is added to a document. Set up content and event listeners here. It can run more than once if the element is moved.
disconnectedCallback: when it is removed. Clean up timers and listeners.
attributeChangedCallback(name, oldValue, newValue): when an attribute listed in the static observedAttributes array changes. It also runs for the attributes present at the start, before connectedCallback.
adoptedCallback: when it moves to a new document, which is rare.
Good practice: keep the attribute as the source of truth for simple values, expose a matching property, and make setup safe to run twice. Because the tag may be in the HTML before the class is defined, the element is first an unknown element and is upgraded when define runs. customElements.whenDefined() returns a promise for that moment.
The result is progressive: if the script fails, the content inside the tag is still in the page.
When the class is defined, the element in the page is upgraded. The log shows the attribute call first, with the value null to easy, and then connected. After changing level to hard, the log gets a new entry and the label updates. Removing the element adds disconnected.
The element is defined after it appears in the HTML, which is common, so test both orders.
Checked in Chrome 156 only. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
Names must contain a dash.
constructor should be light; no attributes or children.
connectedCallback and disconnectedCallback run on add and remove.
Elements already in the HTML are upgraded on define.
Common mistakes
Reading attributes or adding children in the constructor.
Forgetting to list attributes in observedAttributes, so changes are ignored.
Adding listeners in connectedCallback and never removing them, so moving the element adds them twice.
Follow-ups
Why must a custom element name contain a dash?
What does upgrading mean?
Tips
Walk through the order of calls for an element that is upgraded.
Mention that connectedCallback may run more than once.
114.html-css-0114Hardsenior
How can you style a component that uses shadow DOM from the outside, and how does the component style itself?
Shadow DOM isolates styles both ways. The component styles itself with :host and ::slotted, and exposes a styling surface through custom properties, inherited properties and part attributes that the page targets with ::part(). Page rules win over :host and ::slotted.
Full answer
Shadow DOM gives a component its own tree and its own styles. Page styles do not reach inside, and the component's styles do not leak out. This stops clashes, but it raises a question: how can a page change the look on purpose?
Inside the component, in the shadow root's style:
:host matches the element that holds the shadow root, so the component can set its own display, border and padding. A rule from the page, such as my-card { display: none; }, wins over :host, so the page keeps control.
:host(.big) matches the host only when it has the class big.
::slotted(p) styles light DOM elements that were placed into a slot. It matches only direct slotted elements, and page styles still win over it.
Ways for the page to style the inside:
Custom properties inherit through the shadow boundary, so --accent set on the host or on the page is readable inside with var(--accent, teal). This is the cleanest public styling interface.
part and ::part(): the component marks an inner element with part="title", and the page styles it with my-card::part(title) { color: red; }. Only that one element is exposed, with no descendant selectors.
Inherited properties such as color and font-family also pass in.
Plan the public surface on purpose: list the custom properties and parts in your documentation, and treat them like an API.
The host gets a crimson border from the page's custom property. The title is underlined by the outside ::part rule. The slotted paragraph is bold from ::slotted, and its colour comes from the page rule, because the slotted element lives in the page's tree.
A plain page rule such as h3 { color: red; } has no effect on the title inside the shadow tree.
Checked in Chrome 156 only. 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
:host styles the element that owns the shadow root.
::slotted styles direct slotted children.
Custom properties and inherited properties pass in.
part and ::part() expose chosen inner elements.
Page rules beat :host and ::slotted.
Common mistakes
Expecting page CSS selectors to reach inside a shadow root.
Using ::part for many internal elements, which exposes the whole structure.
Forgetting that page styles beat :host and ::slotted rules.
Follow-ups
Why do custom properties pass through the shadow boundary?
What does ::slotted match?
Tips
List the three ways in: custom properties, parts and inherited properties.
Say the page wins over :host, which keeps the author in control.
115.html-css-0115Mediummid
How do named slots and fallback content work in a shadow DOM component?
A slot shows light DOM content inside a shadow tree. The default slot takes children with no slot attribute, named slots take children with a matching slot name, and content inside the slot tag is shown only as fallback. Slotted content stays in the page DOM.
Full answer
A slot is a hole in a component's shadow tree where the page's own content (the light DOM) is shown. The content stays in the page, so the page keeps control of it, search engines and scripts can see it, and page styles still apply to it. The shadow tree only decides where it is drawn.
Rules:
An unnamed slot takes all children that have no slot attribute. This is called the default slot.
A named slot, <slot name="title">, takes children with slot="title". Several children can fill one slot.
Content inside the slot tag is fallback content. It is shown only when nothing is assigned to the slot.
Children that point to a slot name that does not exist are not shown.
Slotted nodes are not moved in the DOM. slot.assignedNodes() and assignedElements() list them, and the slotchange event fires when the assignment changes.
This is a good way to build components such as cards and dialogs that accept their own content, without strings of HTML in attributes.
Order in the light DOM does not set the visual order. The shadow tree decides it. As with order in Flexbox, this can make the reading order differ from the visual order, so keep the structure simple.
The first box shows "Fees" in the header and the text in the body. The second box has no title, so the header shows the fallback "Untitled".
The check reads the slot assignments, which is how a script can tell what is shown.
Checked in Chrome 156 only, by reading the slot assignments. 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
Default slot takes children without a slot attribute.
Named slots match the slot attribute.
Content inside the slot element is fallback.
Slotted nodes stay in the light DOM.
slotchange and assignedElements help scripts.
Common mistakes
Expecting slotted content to be moved into the shadow tree. It stays in the page.
Adding two default slots, where only the first one gets content.
Using slots to reorder content in a way that breaks reading order.
Follow-ups
How do you detect when slotted content changes?
What happens to a child with a slot name that does not exist?
Tips
Explain that the content stays in the light DOM, and the slot only places it.
Name the fallback content as a feature.
116.html-css-0116Hardsenior
How can a custom element take part in a form like a native input?
Set static formAssociated = true and call attachInternals(). Then setFormValue sets what the form sends, and setValidity marks the control valid or invalid. The control still needs keyboard support and a role, so use native elements when they fit.
Full answer
A custom element is not a form control by default. A value inside its shadow tree is not sent when the form is submitted, and the form's validation ignores it. Two things change this.
Set static formAssociated = true on the class. The browser then connects the element to its nearest form (or the one named in its form attribute).
Call this.attachInternals(). The returned ElementInternals object lets the element tell the form what to send and whether it is valid.
Main methods:
internals.setFormValue(value) sets the value that the form sends under the element's name. It can be a string, a File or a FormData.
internals.setValidity({ valueMissing: true }, "Pick a value", anchorElement) marks the control invalid with a message. setValidity({}) makes it valid again.
The internals object also gives form, labels, validity, validationMessage, checkValidity() and reportValidity(). The form itself checks the control when it validates.
Optional callbacks: formResetCallback, formDisabledCallback and formAssociatedCallback, so the control can reset or disable itself with the form.
The element still needs real keyboard support and an accessible role. internals.role and internals.ariaChecked-style properties can set default semantics without adding attributes to the host. Where a native element fits, use it. Build a custom control only when a native one cannot do the job.
With no rating, the form is invalid and the message is "Choose a rating", and the form holds rating=0. After set(4), the form data holds rating=4 and the form is valid.
Test with real keyboard input and a screen reader before using such a control in production.
Checked in Chrome 156 only, by reading the form data and the validity state through ElementInternals. 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
static formAssociated = true connects the element to a form.
attachInternals returns ElementInternals.
setFormValue sets the submitted value.
setValidity joins form validation.
Keyboard support and roles are still your job.
Common mistakes
Using a custom element for a form control when a native element would work.
Forgetting static formAssociated = true, so attachInternals gives no form behaviour.
Setting a form value but not building keyboard support and an accessible role.
Follow-ups
What does setFormValue do?
When is a native control better than a custom one?
Tips
Name the two steps: formAssociated and attachInternals.
Mention setFormValue and setValidity as the main methods.
117.html-css-0117Hardsenior
How do you structure design tokens with CSS custom properties so that a theme change is one edit?
Use primitive tokens for raw values, semantic tokens for roles such as action and surface, and optional component tokens for local hooks. Components read semantic tokens, so a theme redefines only the semantic layer, in one place.
Full answer
Design tokens are named values for colour, spacing, type and so on. In CSS they are custom properties. A good setup has three layers, and each layer refers to the layer before it.
Primitive tokens are the raw palette: --blue-600: #0a58ca, --gray-100: #f2f2f2, --space-2: 8px. Names describe the value, not its use. Components never use them directly.
Semantic tokens say what a value is for: --color-action: var(--blue-600), --color-surface: var(--gray-100). They are the layer that changes with a theme.
Component tokens are optional local hooks: --button-bg: var(--color-action). They give one component its own adjustable value.
To make a dark theme or a second brand, redefine only the semantic tokens inside a selector such as [data-theme="dark"]. All components follow, because they read semantic tokens. Nothing in component CSS changes.
Habits that help:
Name by role, such as --color-text-muted, not by look, such as --light-grey.
Keep a short scale for spacing and type, and use only the scale.
Put tokens on :root and the theme override on an attribute, so a theme can also apply to a part of a page.
Check contrast for each pair in each theme.
Generate tokens from one source file if several platforms use them.
The card is light and the button is blue. After setting data-theme="dark" on the page, the card is dark, the button is a lighter blue, and no component rule changed.
A palette of primitives is not a theme. The theme lives in the semantic layer.
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
Primitive tokens hold raw values.
Semantic tokens name roles and change per theme.
Component tokens are local hooks.
Components should not read primitives.
Check contrast in every theme.
Common mistakes
Using primitive colours directly in components, so a theme needs many edits.
Naming tokens by appearance, such as --dark-blue, which stops making sense in a new theme.
Creating a new token for every one-off value.
Follow-ups
Where do you put the dark theme override?
Why name tokens by role instead of by look?
Tips
Describe the three layers and what changes in a theme.
Say that components read only semantic tokens.
118.html-css-0118Mediummid
How do you let users of a component adjust it with custom properties and still keep safe defaults?
A component reads public custom properties with a fallback, such as var(--badge-bg, default), so it works alone and can be adjusted by setting the property on any ancestor. The fallback covers an unset property, not an invalid value. Use prefixed names and private properties for internals.
Full answer
A custom property can be a small public setting for a component. The component reads the property with a fallback, var(--badge-bg, #e6f0ff), so it works with no setup and changes when someone sets the property.
How it works:
Custom properties inherit. A value set on a parent, on the component itself or on the page flows down to the component.
The fallback in var() is used only when the property is not set (or is the guaranteed-invalid value). It is not used when the property is set to a bad value for the property that uses it. In that case, the declaration becomes invalid at computed time and the property falls back to its inherited or initial value. This is a common surprise.
A fallback can itself use var(): var(--badge-bg, var(--color-surface, white)).
Prefix names with the component, such as --badge-bg, so they do not clash.
Do not set the public property inside the component's own rule on the same element, because that blocks the user's value. Read it with a fallback, and use a private property for internal values.
A clear list of public properties, with defaults, is the interface of the component, like props in a framework.
The first badge uses all defaults. The second changes only the background and keeps the rest. In the third, red is not valid padding, so the padding becomes the initial value 0, and the default 4px 8px is not used.
Check unusual values in your own components, and note in the docs what each property accepts.
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
Custom properties inherit down the tree.
var(--x, fallback) uses the fallback when --x is unset.
An invalid value does not trigger the fallback.
Prefix names with the component name.
Do not override the public property inside the component.
Common mistakes
Expecting the var() fallback to run when a property is set to an invalid value.
Setting the public property inside the component's own rule, which overrides the user's value.
Using generic names such as --color that clash across components.
Follow-ups
What happens to padding when its var() holds an invalid value?
Why prefix custom property names?
Tips
Explain that the fallback applies to unset properties, not to invalid values.
Describe public properties as the component's API.
119.html-css-0119Hardsenior
How do :is() and :where() differ in specificity, and how can :where() make a stylesheet easier to override?
:is() takes the specificity of its strongest argument, while :where() always counts as zero. Use :where() for base styles so any later rule can override them, and fix strong legacy selectors step by step, with layers for larger changes.
Full answer
Both :is() and :where() take a list of selectors and match any one of them. This shortens long rules: :is(h1, h2, h3) a replaces three rules. The difference is in specificity.
:is() takes the specificity of its most specific argument. :is(#nav, .menu) a counts the id, so it is 1,0,1, even when the element matched the class.
:where() always has zero specificity. :where(#nav, .menu) a counts only the a, so it is 0,0,1.
Zero specificity is very useful for defaults, such as a reset or a base style in a library or a design system. Any normal rule written later or earlier can override it, with a plain class, and nobody needs a longer selector or !important. This is how many specificity fights start in old code: a base rule like #page .content ul li a is so strong that every override must be even stronger.
A way to clean up legacy CSS in small steps:
Do not rewrite everything. Wrap new base styles in :where().
For old strong selectors that you can edit, lower them to a class one at a time and test.
Use @layer for larger changes, so layer order beats specificity.
Reserve :is() for convenience, and remember that it can raise specificity.
Also note that :is() and :where() ignore invalid selectors in the list, instead of dropping the whole rule, which is called forgiving parsing.
The first link stays gray. The :where() rule has only the specificity of a class, which is lower than #site a. The second link is green. The :is() rule counts the id, so it beats the plain .link2 blue rule. The button is blue, because the :where(.btn) default has zero specificity, and .primary beats it easily.
Measure with the specificity shown in the browser tools before you restructure rules.
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
:is() uses the highest specificity in its list.
:where() has zero specificity.
Use :where() for defaults and resets.
Lower strong legacy selectors one by one.
Layers can order large groups of rules.
Common mistakes
Using :is() in a base style and unintentionally raising its specificity.
Fighting a strong legacy selector with an even stronger selector or !important.
Rewriting all legacy CSS at once instead of making small safe steps.
Follow-ups
What is forgiving selector parsing?
How do cascade layers help with legacy overrides?
Tips
State both specificities in one line each.
Present :where() as the tool for easy-to-override defaults.
120.html-css-0120Hardsenior
A third-party widget sets inline styles and uses !important. How can your CSS override it safely?
A stylesheet rule with !important beats a normal inline style, and a more specific important rule beats a less specific one. With cascade layers, important rules in earlier layers win. Prefer documented settings, keep selectors narrow and comment every override.
Full answer
Third-party code sometimes sets styles with the style attribute or with !important. The cascade has a fixed order for these cases, and knowing it removes guesswork.
For normal (not important) declarations, the order from weakest to strongest is: the browser's styles, then author styles with layers and specificity, then inline style. An inline style beats a normal rule of any specificity.
For !important declarations, the order reverses between sources:
A stylesheet rule with !important beats a normal inline style. So .widget .title { font-size: 20px !important; } wins over style="font-size: 10px". An inline style with !important beats a stylesheet rule with !important.
Among important rules, the usual specificity and order apply. A more specific !important rule beats a less specific one.
With cascade layers, the order flips for important rules. An important rule in an earlier layer beats an important rule in a later layer, and unlayered important rules are weakest of all. So if the widget's stylesheet is in a later layer, an important rule in an earlier layer of yours wins without a long selector.
Safe approach:
Check first whether the widget has a documented setting, a custom property or a ::part. That is better than any override.
Use the narrowest selector that targets only the widget, such as .widget .title.
Use !important only on the properties you must override, with a comment that explains why.
If you can place your CSS in an earlier layer, use @layer so you can avoid specificity battles.
As a last resort, a script can change the inline style, but widget updates may bring it back.
The first paragraph is blue, because important rules in the earlier layer win. The second is 20px even though it has an inline size, because the stylesheet rule is important. The third is green, because the more specific important rule wins.
Document every override, so the next person can remove it when the widget is fixed.
html
<style>
@layer ours, widget;
@layer widget { .w .a { color: red !important; } }
@layer ours { .w .a { color: blue !important; } }
.w .b { font-size: 20px !important; }
.w .c { color: red !important; }
.w .c.fix { color: green !important; }
</style>
<div class="w">
<p class="a" id="a">Layered</p>
<p class="b" id="b" style="font-size: 10px">Inline loses to !important</p>
<p class="c fix" id="c">Specific important wins</p>
</div>
Checked in Chrome 156 only. The widget is a stand-in written for the example, not a real third-party 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
Normal inline styles beat normal stylesheet rules.
Important stylesheet rules beat normal inline styles.
Among important rules, specificity decides.
Layer order is reversed for important rules.
Prefer documented settings and comment overrides.
Common mistakes
Raising specificity again and again instead of using layers or the widget's own settings.
Using !important on whole blocks of CSS.
Overriding widget internals that change with each widget update, with no comment.
Follow-ups
Which wins, an inline style or a stylesheet rule that has !important?
Why is a documented widget setting better than an override?
Tips
State the key rule: an important stylesheet rule beats a normal inline style.
Say that layers reverse the order for important rules.