Questions 141–160 of 193 · 0 of 20 on this page marked learned
141.html-css-0141Easyfresher
There is a small gap under an image inside a box, with no margin or padding set. Why is it there, and how do you remove it?
An img is inline, so it sits on the text baseline, and the line box keeps room below it for descenders. That creates the gap. Set img to display: block, or use vertical-align: top, middle or bottom.
Full answer
An img is an inline element by default. Inline content sits on the text baseline of its line. Below the baseline, the line box keeps room for the descenders of letters such as g and y. So the line is a little taller than the image, and a gap appears under it. The size depends on the font and the line height of the parent. It exists even when the parent holds no text, because the browser still builds the line.
You can remove the gap in a few ways.
img { display: block; } is the simplest. The image is no longer in a line, so there is no baseline. Use margin-inline: auto if you need to centre a block image.
img { vertical-align: top; } (or middle or bottom) moves the image off the baseline. It keeps the image inline, which helps when it sits next to text.
Setting line-height: 0 or font-size: 0 on the parent also works, but it can affect other content inside, so it is a weaker fix.
A modern reset often sets img, svg, video { display: block; max-width: 100%; } for this reason. The same gap appears for svg, canvas, video and input type="image", and for inline-block elements.
To find the cause, open the developer tools, select the parent and look at its height compared with the image height. The difference is the baseline gap. Highlight the line box if your tools show it.
The first box is taller than its 50px image, so a pink gap shows below it. The second and third boxes are exactly 50px high.
This is a normal part of how inline layout works, and it is not a browser bug.
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
Images are inline and sit on the baseline.
The line box reserves descender space below.
display: block removes the baseline problem.
vertical-align moves the image off the baseline.
The same happens with svg, video and canvas.
Common mistakes
Adding a negative margin to hide the gap.
Setting a fixed height on the parent to cut it off.
Not knowing it happens with svg, video and canvas as well.
Follow-ups
Does the gap depend on the parent's font?
Which other elements show the same gap?
Tips
Explain baseline and descender space in one or two sentences.
Give display: block as the first fix and vertical-align as the second.
142.html-css-0142Hardsenior
A grid column set to 1fr is wider than expected and pushes the page sideways. What is the cause and the fix?
A 1fr track has an automatic minimum of min-content, so wide content such as a long word or code line stops it from shrinking and the track overflows the container. Use minmax(0, 1fr) or min-width: 0 on the item, and let the content wrap or scroll.
Full answer
1fr is not a fixed share of the width. The fr unit divides the free space, and a grid track has an automatic minimum size. For 1fr the track is really minmax(auto, 1fr). The auto minimum means the track will not shrink below the min-content size of its items. If an item contains something that cannot wrap, such as a long word, a wide image, a pre block, a table or an input with a fixed width, then the track grows to fit it. The column becomes wider than the container, and the page may get a horizontal scrollbar.
This is the same problem as a flex item with min-width: auto, and the fix is similar: allow the track or the item to shrink.
Fixes:
Use minmax(0, 1fr) instead of 1fr. The zero minimum lets the track shrink below the content, and then the content can overflow the track or wrap, depending on its own rules.
Or set min-width: 0 on the grid item that holds the wide content.
Then decide what the wide content should do. Give a pre or a table overflow-x: auto in its own box, let long words break with overflow-wrap: anywhere, and give images max-width: 100%.
Setting only the track to minmax(0, 1fr) stops the page from stretching, but the content can then spill over. Handle the content too.
repeat(auto-fit, minmax(200px, 1fr)) has a similar trap on very narrow screens: when the container is narrower than 200px, the track cannot be smaller than 200px. Use minmax(min(200px, 100%), 1fr) to prevent it.
In the first grid, the second column grows to fit the code line, so the grid is wider than 300px. In the second grid, the column stays at 200px (300 minus 100 minus the 8px gap), and the code scrolls inside its own box.
Look at the track sizes in the grid inspector of your browser tools to see which one grew.
html
<style>
.layout { display: grid; grid-template-columns: 100px 1fr; width: 300px; gap: 8px; }
.fixed { grid-template-columns: 100px minmax(0, 1fr); }
pre { margin: 0; background: #eee; overflow-x: auto; }
</style>
<div class="layout" id="bad"><nav>Menu</nav><main id="m1"><pre>const a = "a very long line of code that cannot wrap at all";</pre></main></div>
<div class="layout fixed" id="good"><nav>Menu</nav><main id="m2"><pre>const a = "a very long line of code that cannot wrap at all";</pre></main></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
1fr is minmax(auto, 1fr).
Long words, pre blocks and wide media set a large minimum.
minmax(0, 1fr) lets the track shrink.
Wide content needs its own overflow rule.
Use min() inside minmax for auto-fit.
Common mistakes
Setting width: 100% on the item and expecting the track to obey.
Fixing the track with minmax(0, 1fr) but not giving wide content its own scroll or wrapping.
Using minmax(200px, 1fr) in auto-fit with no min() for very small screens.
Follow-ups
What is the real value of 1fr?
How is this related to flex items and min-width: auto?
Tips
Explain that 1fr has an automatic minimum, and what content sets it.
Give minmax(0, 1fr) as the fix, then handle the content.
143.html-css-0143Easyfresher
A child has height: 50% but it does not change. Why, and how do you fix it?
A percentage height needs the parent's height to be definite. With an auto-height parent the percentage is treated as auto, to avoid a circular dependency. Give the parent a height, use viewport units, or use flex or grid.
Full answer
A percentage height is a share of the height of the containing block. If the parent's height is auto, which means it depends on its content, the browser cannot compute the share, because the child's height would then change the parent's height, and the parent's height would change the child's. To avoid the loop, a percentage height on a child of an auto-height parent is treated as auto.
Percentage widths do not have this problem, because a block's width comes from its parent and not from its content.
Fixes depend on what you want:
Give the parent a definite height, such as height: 300px. Then 50% works. For a full-page layout, every ancestor in the chain must have a height: html, body { height: 100%; } and so on. Using min-height on the parent does not count as definite for this purpose in older rules, so check the result.
Use viewport units for the page: height: 50vh ignores the parent entirely.
Use Flexbox or Grid. In a flex column with a set height, flex: 1 on a child makes it fill the space. In grid, grid-template-rows: 1fr 1fr splits the height without percentages.
For a box with a shape such as a square, use aspect-ratio instead of a height percentage.
In most layouts, Flexbox or Grid is the better choice than a chain of height: 100%.
In the first box the child ignores 50% and is as high as its text. In the second box the child is 100px high. In the third box the child takes all 200px of the height through flex: 1.
When a percentage height has no effect, check each ancestor for a definite height.
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
Percentage heights need a definite parent height.
An auto-height parent makes the percentage act as auto.
Width percentages work because width comes from the parent.
Set heights up the chain, or use vh units.
Flex and grid usually replace the percentage.
Common mistakes
Setting height: 100% on a child but leaving the parent with auto height.
Fixing it by setting height on every ancestor when flex or grid would be simpler.
Confusing it with percentage width, which works with an auto-height parent.
Follow-ups
Why do percentage widths not have this problem?
How do you make a child fill the rest of the parent's height?
Tips
Explain the circular dependency: the parent's height depends on the child.
Give the three fixes: definite parent height, viewport units, flex or grid.
144.html-css-0144Mediummid
What do flex: 1, flex: auto, flex: none and flex: 0 1 200px mean, and when does each give a different result?
flex combines grow, shrink and basis. flex: 1 is 1 1 0% and makes equal shares, flex: auto is 1 1 auto and adds free space to the content size, and flex: none is 0 0 auto and keeps the size fixed. A single number sets grow, and the basis becomes 0.
Full answer
flex is a shorthand for three properties: flex-grow, flex-shrink and flex-basis. The basis is the starting size before growing or shrinking.
flex: 1 means 1 1 0%. The starting size is zero, so all the free space is shared by the growth factors. Items with flex: 1 become equal in width, whatever their content.
flex: auto means 1 1 auto. The starting size is the content or width size. Free space is added on top of that, so items with more content stay wider.
flex: none means 0 0 auto. The item neither grows nor shrinks. It keeps its width or content size. This is good for a fixed icon or a sidebar.
flex: 0 1 200px means do not grow, can shrink, start at 200px. It is a width that gives way when space is short.
flex: 2 makes an item take twice the share of an item with flex: 1.
flex-basis overrides width in a row, and height in a column. flex-basis: 0 and width: 0 are not the same in all cases because of the minimum size rules.
A single number is read as flex-grow, and the basis becomes 0, which is why flex: 1 gives equal columns. A length alone is read as the basis.
Items also have min-width: auto, so a long word can prevent shrinking. Set min-width: 0 on the item when text must wrap or truncate.
In the first row, both items are 150px wide. In the second row, the long item is wider than the short one, because each starts at its content size and then both share the extra space. In the third row the first item is exactly 100px and the second takes the remaining 200px.
Check the result when the text is longer, because wrapping changes the sizes.
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 is grow, shrink and basis.
flex: 1 is 1 1 0% and gives equal widths.
flex: auto starts from the content size.
flex: none is rigid.
min-width: 0 lets text shrink.
Common mistakes
Using flex: 1 and expecting content-based widths.
Setting width on a flex item and being surprised when it shrinks.
Forgetting min-width: 0 when text must wrap in a flex item.
Follow-ups
What does a single number in flex mean?
Why can an item with a width still shrink?
Tips
Give the expanded form of 1, auto and none.
Explain the difference between 1 and auto using the starting size.
145.html-css-0145Hardsenior
How do you make a wide data table readable on a phone, and what must you not break?
Wrap the table in a labelled scroll area, hide low-value columns, or turn rows into cards with display: block and data-label text. When changing display on table parts, restore table roles and keep the header available to assistive tools.
Full answer
A table with many columns does not fit on a small screen. There are three main approaches.
Horizontal scroll: put the table in a wrapper with overflow-x: auto, and give the wrapper tabindex="0", a role="region" and a label so keyboard users can scroll it. It keeps the table intact and is the safest choice. Pin the first column with position: sticky if users need to keep their place.
Hide less important columns on small screens. This hides data, so only use it for information that is not needed.
Stack each row as a card. Each cell shows its column name before its value. This is easy to read, but it takes more work to keep accessible.
For the card version:
In a media query, set display: block on table, tbody, tr and td, and hide the thead visually.
Copy each column name into a data-label attribute on the cells, and show it with td::before { content: attr(data-label); }.
Setting display: block on table parts can remove the table semantics for some browsers and screen readers. Restore them with role="table", role="row", role="cell" and role="columnheader", and keep the header row available to assistive tools by hiding it with a visually hidden style, not display: none.
Text from content is not always read by every screen reader, so test it.
Keep a real table in the HTML. Do not change the HTML for small screens.
Choose scrolling when the data must be compared across columns. Choose cards when each row is a record, such as an order or a person.
On a wide screen it is a normal table. Under 500px each row becomes a small card with "Course" and "Price" before the values, and the header is moved off screen but still available to assistive tools.
Test with a screen reader in both layouts, because changing display values can change what is announced.
Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
Horizontal scroll keeps the table intact.
Cards use display: block and data-label with attr().
display changes can remove table semantics.
Restore roles and keep the header available.
Choose by whether users compare columns.
Common mistakes
Hiding the thead with display: none, so screen readers lose the column names.
Changing display on table elements and not restoring the roles.
Using cards when users need to compare columns.
Follow-ups
When is horizontal scroll better than cards?
Why use a visually hidden header instead of display: none?
Tips
List the three options and when each fits.
Warn about losing table semantics when changing display.
146.html-css-0146Mediummid
A modal locks page scroll and the page jumps sideways. What causes it, and which CSS properties help?
Hiding the page scrollbar with overflow: hidden removes its width and shifts the layout on systems with classic scrollbars. scrollbar-gutter: stable reserves that space, and overscroll-behavior: contain stops scrolling inside a modal list from scrolling the page behind. Focus still needs inert or a native dialog.
Full answer
A common way to lock scrolling behind a modal is overflow: hidden on the body or html. On systems with classic scrollbars, which take space, the scrollbar disappears and the page gets wider by that amount, so all content jumps sideways by the width of the bar. On phones and systems with overlay scrollbars there is no jump.
Fixes:
scrollbar-gutter: stable on the scrolling element keeps room for the scrollbar even when it is not needed, so the width does not change when overflow changes. It is a newer property, so check the support table. scrollbar-gutter: stable both-edges also adds space on the other side so content stays centred.
Compensate with padding: measure the bar width (window.innerWidth - document.documentElement.clientWidth) and add it as right padding while locked. This works everywhere, but needs script.
The other problem is scroll chaining. When a user scrolls the modal's own list to the end and keeps scrolling, the page behind starts to scroll. overscroll-behavior: contain on the inner scroll area stops the scroll from passing to the parent. overscroll-behavior: none also disables effects such as pull-to-refresh and bounce at the edge of that element. Use it with care, because it changes browser habits.
Remember that locking page scroll does not stop keyboard focus from reaching content behind the modal. Use inert or a native dialog for that. Also, a native dialog opened with showModal() lets you style body:has(dialog[open]) for the lock.
The computed values show that the gutter is reserved on the page and that scroll chaining is contained in the panel. In a desktop browser with classic scrollbars, the layout width stays the same after the lock is added.
The test browser here hides scrollbars, so the width jump itself was not measured. Check it on a desktop browser with visible scrollbars.
The test browser hides scrollbars, so the width jump was not measured. The check read the computed values 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
overflow: hidden removes the scrollbar and shifts the layout.
Check on a desktop browser with visible scrollbars.
Common mistakes
Using overflow: hidden on the body and ignoring the layout jump on desktop.
Using overscroll-behavior: none everywhere, which removes useful browser behaviour.
Thinking that a scroll lock also traps keyboard focus.
Follow-ups
What does scroll chaining mean?
Why is a scroll lock not a focus trap?
Tips
Explain why the page jumps: the scrollbar width disappears.
Name scrollbar-gutter and overscroll-behavior, and say what each solves.
147.html-css-0147Hardsenior
A page shows a user's comment. How do you insert it safely, and what goes wrong with innerHTML?
Treat user input as text: set it with textContent or build elements with createElement, and use innerHTML only for trusted or sanitized markup. Escape for the exact context, never place user input in scripts or handler attributes, and add a CSP as a second layer.
Full answer
If a page puts user input into HTML as markup, the user can add their own markup, including scripts or event handlers. This is cross-site scripting (XSS). The attacker's code runs with the page's rights, so it can read data, act as the user and change the page.
The fix is to treat input as text and not as markup.
Use textContent (or innerText) to set text. The browser puts the characters in as text, so <b> shows as the characters <b> and does nothing.
Create elements with document.createElement and set properties, instead of gluing strings.
Use innerHTML only for markup that you wrote, or that has been sanitized by a trusted library. Newer browsers also offer sanitizer APIs, but check the support table first.
Where a string must be built, escape the five characters & < > " ' for the context. Escaping depends on where the value goes: in element text, in a quoted attribute, in a URL or in a script. Never put user input into a script, an event handler attribute or a javascript: URL. Check URLs for an allowed scheme before using them in href.
In templates on the server, use the engine's automatic escaping, and do not turn it off.
Layers of defence:
A Content Security Policy (CSP) header can block inline scripts and unknown sources, which reduces the damage of a mistake. It does not replace escaping.
Cookies with HttpOnly cannot be read by page scripts.
Validate input on the server, but escape on output, because the right escaping depends on where the data is shown.
Calling showSafe() shows the characters of the comment, and nothing runs. Calling showUnsafe() creates a real image element whose onerror handler runs, and the counter goes up. The escape helper turns the five characters into entities, which is correct for element text and quoted attributes only.
This example runs the unsafe case on purpose in a test page. Never do this with real user data.
The unsafe case is run on purpose in a test page to show the problem. Never do this with real user data. 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
XSS happens when user input becomes markup.
textContent inserts text, not markup.
Use innerHTML only for trusted or sanitized markup.
Escape for the right context on output.
CSP and HttpOnly cookies reduce damage.
Common mistakes
Using innerHTML with user input.
Escaping once and using the result in a different context, such as a URL.
Relying only on a CSP or only on input validation.
Follow-ups
Why is escaping done on output and not on input?
Which characters must be escaped in element text?
Tips
Explain the risk in one sentence, then give the textContent fix.
Mention escaping depends on the context, and name CSP as a second layer.
148.html-css-0148Mediummid
What do preconnect, dns-prefetch, preload and prefetch do, and when can they hurt?
dns-prefetch resolves a host early, preconnect opens the full connection, preload fetches a file needed by the current page at high priority and needs as, and prefetch fetches a likely next resource at low priority. Too many hints compete with needed files, so use few and measure.
Full answer
Resource hints are link elements in the head that tell the browser about work it can do early.
dns-prefetch resolves the host name of another site early. It is cheap and widely supported, and it is a fallback for preconnect.
preconnect opens the whole connection early: the name lookup, the network connection and the security handshake. Use it for a few important other-origin hosts that you will definitely use soon, such as a font host or an image CDN. Add crossorigin when the resource is loaded with CORS, as fonts are.
preload tells the browser to fetch a specific file now, for the current page, with a high priority. Use it for something the browser would find late, such as a font used in CSS, a hero image used as a CSS background, or a script that is loaded by another script. It needs as (for example as="font", as="image") so the browser sets the right priority and headers.
prefetch fetches a resource at low priority for a likely next page, such as the script for the next step in a flow. It is used only when the browser is idle.
modulepreload is the same idea for JavaScript modules.
How they can hurt:
Too many hints compete for bandwidth with the files the page needs now. Preload is strong. A preloaded file that the page does not use within a short time causes a console warning and wastes data.
Preconnect to many hosts opens many connections, and unused connections are closed again.
A preload without the right as or crossorigin can fetch the file twice.
Prefetching on slow or limited connections wastes the user's data.
Rule: hint only for what you have measured to be late, and keep the list short. Test with the network panel.
The page content is unchanged, but the browser starts the connection to the font host and the font download early. The next step's stylesheet is fetched later at low priority.
Browser tools show the priority and the time for each request, which is the right place to confirm a gain.
The check read the link elements and their attributes. Network timing and priorities were not measured. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
dns-prefetch resolves names; preconnect opens the connection.
preload is for current-page files found late and needs as.
prefetch is low priority for a likely next page.
Fonts need crossorigin on preload.
Too many hints hurt; measure.
Common mistakes
Preloading many files, so the important ones are slowed down.
Preloading a font without crossorigin, which causes a second download.
Preconnecting to hosts that the page does not use early.
Follow-ups
What does the as attribute do on preload?
Why is dns-prefetch used with preconnect?
Tips
Give a one-line meaning for each of the four hints.
Say that hints must be measured and kept few.
149.html-css-0149Easyfresher
When do you use article, section, aside and div?
article is self-contained content, section is a thematic group that should have a heading, aside is related but removable content, and div has no meaning. A section with an accessible name is exposed as a region, and aside as complementary.
Full answer
These elements all group content, but they carry different meaning.
article is a self-contained piece that makes sense on its own and could be shared or reused: a blog post, a news story, a product card in a list, a comment. A test is whether it would still make sense in a feed or an email.
section is a thematic group of content, usually with a heading. It is part of a larger whole, such as "Pricing" and "Reviews" on a page. A section without a heading or a name is just a div with extra words. With an accessible name (for example aria-labelledby pointing to its heading), it becomes a region landmark for screen reader users.
aside is content that is related to the main content but could be removed without breaking it: a sidebar, a pull quote, a box of related links. It is a complementary landmark.
div has no meaning. Use it when you need a box for styling or scripting and no other element fits.
Other points:
Do not use section just to apply CSS. Use div for that.
Each article and section should usually have a heading, so a user who moves by headings can understand the page.
Pick the element by meaning, then style it. The correct element can give you landmarks for free, and too many unnamed landmarks make navigation noisy.
Use header, footer, nav and main for page-level parts. header and footer inside an article or section are not page-level landmarks.
The post is an article that can stand alone. The Basics block is a named section, so it appears as a region. The related links are an aside, which screen readers list as complementary content. The last box is a plain div because it has no meaning.
Check the outline with a landmarks list in a screen reader or browser tools.
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
article stands on its own.
section groups a theme and needs a heading.
aside is related, removable content.
div carries no meaning; use it for styling.
Name a section to make it a region.
Common mistakes
Using section for every wrapper because it sounds semantic.
Using article and section with no headings.
Adding many landmarks with no names, which makes navigation noisy.
Follow-ups
What makes a section a region landmark?
Is a header inside an article a page-level banner?
Tips
State the meaning of each in one line, and say div means none.
Give the self-contained test for article.
150.html-css-0150Easyfresher
What does the hidden attribute do, and why can an author style break it?
hidden makes the browser hide an element with display: none, and a script can toggle el.hidden. Because the browser's rule is weak, an author rule such as display: flex shows the element anyway. Add [hidden] { display: none !important; } to avoid this.
Full answer
The hidden attribute says that an element is not relevant right now. The browser's built-in stylesheet turns it into display: none, so the element is not drawn, not focusable and not read by screen readers. It is a good, simple way to hide a panel, an error message or a dialog until it is needed. A script can change it with el.hidden = true or false.
The gotcha: the built-in rule is a very weak rule, [hidden] { display: none } in the browser's own style sheet. Any author rule that sets display on the same element has a higher priority. If your CSS says .panel { display: flex; }, then a .panel with hidden is still visible. The attribute is present, but nothing hides the element. This is a classic bug with flex and grid components.
Fixes:
Add a rule [hidden] { display: none !important; } to your base styles. This is one of the few good uses of !important.
Or write component rules so that they do not set display on the hidden state, for example .panel:not([hidden]) { display: flex; }.
Compared with a class that sets display: none, hidden is shorter, has a clear meaning and is respected by assistive technology in the same way. Use CSS classes when the hiding depends on screen size, because hidden is not responsive.
There is also hidden="until-found". The content stays hidden, but find-in-page and links to a fragment can reveal it, and the browser fires a beforematch event. It is useful for collapsed text that should still be searchable. It is a newer feature, so check the support table and expect plain hidden behaviour in browsers that do not know it.
The first panel is shown even though it has hidden. The second is hidden because an author rule with the same priority brings back display: none. The third is hidden by the browser's default rule.
Add one global hidden rule so you never see this bug.
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
hidden maps to display: none in the browser's style sheet.
Using hidden on an element that also has an author display rule, and expecting it to disappear.
Using hidden for something that should hide only on small screens.
Hiding important content with hidden and expecting find-in-page to reach it.
Follow-ups
Why is hidden content not read by screen readers?
What does hidden="until-found" change?
Tips
Explain that hidden is a weak default rule, so author display rules beat it.
Give the global [hidden] rule as the fix.
151.html-css-0151Easyfresher
How do you use an inline SVG icon so that it scales, follows the text colour and stays accessible?
Give the svg a viewBox so it scales, use currentColor so it follows the text colour, and hide decorative icons with aria-hidden. Icon-only controls need an accessible name from visually hidden text or aria-label.
Full answer
An inline svg in the HTML is part of the page. CSS and scripts can style it, and it needs no extra file request.
Scaling: the viewBox attribute defines the drawing's own coordinate system, such as viewBox="0 0 24 24". The width and height set the size on the page. The drawing scales to fit, and keeps its shape (preserveAspectRatio defaults to keeping the ratio). Without a viewBox, the SVG cannot scale and may be cut off.
Colour: set fill="currentColor" (or stroke="currentColor") on the shapes. currentColor is the text colour of the element, so the icon follows the color of its parent. A hover colour on the button changes the icon, with no extra rule. This also works in forced colors mode.
Accessibility has two cases.
Decorative icon next to text, such as a search icon beside the word "Search": hide it with aria-hidden="true" and focusable="false", so it adds no noise.
Meaningful icon with no text, such as an icon-only button: give the control a name. Best is visually hidden text in the button, or aria-label on the button. For a standalone image, use role="img" on the svg with aria-labelledby pointing to a title element inside it, or an aria-label.
A title inside an SVG may show a tooltip in some browsers, but it should not be the only way to give a name, because support in assistive technology varies.
If the same icon is used many times, define it once with symbol and reuse it with <use href="#id">. This keeps the markup small.
The search icon is 24 by 24 pixels and is drawn in the button's blue. On hover, both the text and the icon turn red. A screen reader reads "Search" and "Close" and ignores the drawings.
Check the icons at a large zoom and in forced colors mode.
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
viewBox sets the drawing's coordinates and lets it scale.
currentColor follows the text colour.
Decorative icons use aria-hidden.
Icon-only buttons need an accessible name.
symbol and use reuse icons.
Common mistakes
Leaving out the viewBox, so the icon cannot scale.
Using a fixed fill colour, so the icon ignores the text colour and hover state.
Leaving an icon-only button with no accessible name.
Follow-ups
What does currentColor refer to?
How do you reuse one icon many times?
Tips
Name the three points: viewBox, currentColor, accessible name.
Separate decorative icons from meaningful ones.
152.html-css-0152Easyfresher
How do you draw a triangle or a tooltip arrow with CSS only?
For the border method, use a zero-size element with transparent side borders and one coloured border. With clip-path, cut a box with polygon(). A tooltip arrow is a positioned pseudo-element with the same colour as the tooltip.
Full answer
There are two simple ways.
The border method uses the way borders meet at a corner. Borders are cut diagonally where they join. If an element has width: 0 and height: 0, only the borders are left, and each border is a triangle. Make the sides next to the point transparent and give one side a colour:
The coloured border is the side the point faces away from: a coloured border-bottom makes a triangle that points up.
The clip-path method cuts a normal box to a triangle: clip-path: polygon(50% 0, 100% 100%, 0 100%). It is easier to read, easy to size with width and height, and the shape can have a background, a gradient or a size in percentages. The cut-away parts are not clickable and a shadow is clipped.
A tooltip arrow is usually a pseudo-element on the tooltip. Make it position: absolute, place it on an edge of the tooltip, for example bottom: 100%, and left: 12px. Use the same colour as the tooltip background.
A rotated square is a third way: a small box with transform: rotate(45deg) and a background, half hidden behind the tooltip. It also allows a border on the arrow.
Use CSS shapes for simple pointers. For anything complex, use an SVG, which is easier to adjust and to keep sharp.
The tooltip has a small upward arrow at its top edge, 12px from the left. The red box is cut to a triangle with its point at the top centre.
Check the arrow position when the tooltip text gets longer, and place it at the right edge of the trigger.
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
Borders meet diagonally, so a zero-size box shows triangles.
The coloured border is on the side opposite the point.
clip-path: polygon() makes a triangle from a box.
Tooltip arrows are positioned pseudo-elements.
Use SVG for complex shapes.
Common mistakes
Giving the arrow element a width or height, so the border triangle becomes a trapezoid.
Using a different colour from the tooltip background, so the arrow looks detached.
Using clip-path on the same element as a shadow and losing the shadow.
Follow-ups
Why does a zero-size element with borders show triangles?
What are the downsides of clip-path for a tooltip arrow?
Tips
Describe the border method and the clip-path method.
Mention that coloured border faces away from the point.
153.html-css-0153Mediummid
How do you keep content out of the notch and the home bar area on phones?
Add viewport-fit=cover to the viewport meta tag to draw edge to edge, then pad with env(safe-area-inset-top, right, bottom, left), combined with max() or calc(). Insets are 0 on screens without a notch, and a plain value before the env line works as a fallback.
Full answer
Some phones have a notch, rounded corners or a home indicator bar. If a page uses the whole screen, parts of the content can sit under these areas. The browser handles this by default: it keeps the page inside the safe area. When you want a design that reaches the screen edges, you must handle it yourself in two steps.
Opt in with the viewport meta tag: <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">. With viewport-fit=cover, the page is drawn over the whole screen, including the unsafe areas.
Add padding with the environment variables: env(safe-area-inset-top), env(safe-area-inset-right), env(safe-area-inset-bottom) and env(safe-area-inset-left). They are the sizes of the unsafe areas, and they are 0 on screens without them.
The first line is the fallback for browsers that do not understand env(). The second keeps at least 16px of space, and uses the larger inset when there is one. max() and calc() can combine the values: calc(16px + env(safe-area-inset-bottom)) adds them instead.
env() also takes a fallback value: env(safe-area-inset-bottom, 0px). The variables are only filled when viewport-fit=cover is set, and when the phone is turned sideways the left and right insets matter.
Do not use viewport-fit=cover without handling the insets, because then content can be hidden under the notch. If you do not need edge-to-edge design, skip it.
On a desktop browser the insets are 0, so the bar has 12px of padding on every side. On a phone with a home bar, the bottom padding grows to the height of the bar, so the text stays clear of it.
The notch itself was not tested here. Check on a real device or in a simulator that has a notch.
On a desktop browser the insets are 0. The notch was not tested, so check on a device or a simulator. 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
viewport-fit=cover lets the page reach the screen edges.
env(safe-area-inset-*) holds the unsafe area sizes.
Use max() or calc() to combine with normal padding.
Insets are 0 where there is no notch.
Test on a device with a notch.
Common mistakes
Using viewport-fit=cover and leaving out the env() padding.
Forgetting a fallback for browsers that do not support env().
Ignoring the left and right insets when the phone is turned sideways.
Follow-ups
What value does env(safe-area-inset-bottom) have on a desktop?
What does viewport-fit=cover change?
Tips
State the two steps: viewport-fit=cover and env() insets.
Show max() or calc() as the way to combine with normal padding.
154.html-css-0154Easyfresher
What are void elements, and why does a self-closing div break the page?
Void elements such as br, img and input have no end tag and no content. A trailing slash is ignored in HTML, so a self-closing div is an opening tag that swallows the next elements. Check the real DOM in the developer tools.
Full answer
A void element has no content and no end tag. The list is short: area, base, br, col, embed, hr, img, input, link, meta, source, track and wbr. The parser closes them at once, so <br> is a complete element and </br> is an error.
In HTML, a slash at the end of a tag, as in <br/>, is allowed on void elements but means nothing. The parser ignores it. This is different from XML and from JSX, where every element must be closed. The habit of writing <div /> comes from those languages, and it is a bug in HTML. For a non-void element, the slash is ignored, so <div/> is an opening tag. Everything after it becomes the content of that div until a closing tag appears or the parent ends.
Results:
A "self-closed" div or span swallows the following elements into its box. Styles and layout then look wrong, and the cause is hard to see in the source.
Void elements cannot have children. Setting innerHTML on an img does nothing, and a script cannot append into an input.
<script src="a.js" /> is not closed either. The browser waits for </script>, and the following markup can be treated as script text.
Use the developer tools to check the real DOM. It shows what the parser built, which can differ from the source.
The first section has three void elements, and each has no child nodes. In the second section, the div is never closed, so the paragraph ends up inside it. A script can confirm this by reading p.parentElement.className, which gives x.
When a linter or a code formatter warns about this, fix the source and do not rely on the parser's recovery.
html
<section id="a"><img src="/a.png" alt="" id="img"><br id="br"><input id="inp"></section>
<section id="b"><div class="x"/><p id="p">I am inside the div</p></section>
Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
Void elements have no content and no end tag.
The trailing slash is ignored in HTML.
A self-closed div or script stays open.
Void elements cannot have children.
Inspect the parsed DOM, not only the source.
Common mistakes
Writing <div /> or <span /> and expecting an empty element.
Writing </br> or </img> end tags.
Self-closing a script tag with a src attribute.
Follow-ups
Why does JSX need the slash and HTML does not?
How can you see the DOM the parser really built?
Tips
Give the list of common void elements from memory: br, hr, img, input, meta, link.
Say that the trailing slash is ignored in HTML and explain the div consequence.
155.html-css-0155Mediummid
The source has no tbody, no closing li and no html or body tags, yet the DOM has them. How does the HTML parser decide this?
The HTML parser follows a fixed algorithm that adds implied elements such as html, head, body and tbody, closes optional tags such as li and p, and repairs misnested markup. The DOM is what CSS and scripts see, so debug there.
Full answer
The HTML parser never stops with a syntax error. It follows a fixed algorithm that repairs mistakes, and the result is a DOM tree that is always valid. Two kinds of repair matter.
Implied elements: some elements can be left out, and the parser adds them.
html, head and body are created even when the source has none. A page that starts with <title>Hi</title><p>text gets all three.
tbody is added inside a table when rows appear without it. This is why the selector table > tr never matches, while table > tbody > tr does.
Optional end tags: a li is closed when the next li starts, a p is closed when a block element such as another p or a div starts, and td and tr end when the next cell or row begins.
Error recovery: when the markup breaks the rules, the parser picks a repair. For example, a p cannot contain a div, so the div closes the paragraph and the later </p> creates an empty paragraph. Another rule moves a misplaced element out of a table. The exact rules are in the specification, and every browser follows the same ones, so the DOM is the same everywhere.
What this means in practice:
The source and the DOM can differ, so debug in the Elements panel and not in the file.
CSS and scripts see the DOM. A child selector written for the source can fail.
Leaving out optional tags is legal, but writing them makes the structure clear to readers.
The list has two li elements, because each one is closed by the next. The two paragraphs are siblings, and the second is not inside the first. The table gets a tbody that is not in the source. A document parsed from a tiny string still has head and body.
If a layout bug looks impossible, compare the source with the DOM before changing any CSS.
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 parser repairs errors and always builds a tree.
html, head, body and tbody are implied.
li, p, td and tr end tags are optional.
All browsers follow the same algorithm.
Debug in the DOM, not in the source.
Common mistakes
Writing the selector table > tr and finding no match.
Debugging from the source file and ignoring the DOM that the parser built.
Relying on optional end tags in a team that does not know the rules.
Follow-ups
Why does a missing end tag on a p not nest the next p inside it?
Which tool shows the real DOM?
Tips
Say that the parser always produces a tree and never throws a syntax error.
Give the tbody example, because it breaks child selectors.
156.html-css-0156Hardsenior
A div inside a table jumps out above it, and a p with a div leaves an empty paragraph. What rules cause this?
Inside a table, content that is not a table part is moved before the table (foster parenting). A p is closed when a block element starts, and the later end tag creates an empty paragraph. A link cannot contain another link, and interactive elements should not be nested.
Full answer
When markup is nested in a way that the content model does not allow, the parser applies recovery rules. Three of them often puzzle people.
Foster parenting: inside a table, only table parts are allowed. If other content, such as a div, text or a span, appears where the parser expects a row or a cell, the parser moves that content to just before the table. Text between rows ends up above the table, and a stray div sits above it. A common cause is a template or a component that wraps rows in a div.
Paragraph closing: a p cannot contain block-level content such as div, ul, table or h2. When one starts, the parser closes the open p first. A later </p> then has no open paragraph, so the parser creates an empty one. This is why a stray empty paragraph with a margin sometimes appears in the layout.
Nested interactive content: an a cannot contain another a. The second start tag closes the first. A button inside an a is not repaired by the parser, but it is invalid, because it creates two controls for one click and confuses keyboard and screen reader users. The same goes for a form inside a form, where the inner form tag is ignored.
How to fix these:
Keep table content to rows and cells. Put wrappers outside the table, or use CSS grid with proper roles in place of a real table when the structure must be flexible.
Use div or section as a wrapper for block content and keep the p for text.
Run the page through an HTML checker, and compare the DOM with the source when the layout is strange.
The div is moved before the table, so it is the table's previous sibling. The paragraph is closed by the div, so the block is a sibling of the paragraph, and the final </p> makes one more empty paragraph after it. The two anchors become two separate links.
These are rules from the specification, so all current browsers agree.
The page was parsed by Chrome 156 and the resulting DOM was read. Other parsers follow the same HTML standard, but only Chrome was run. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
Foster parenting moves stray table content above the table.
Block elements close an open p.
A stray </p> creates an empty paragraph.
Nested links are split by the parser.
Compare the DOM with the source when layout looks wrong.
Common mistakes
Wrapping table rows in a div in a component and finding the wrapper above the table.
Putting a div or ul inside a p.
Placing a button or a link inside another link.
Follow-ups
What happens to text placed between table rows?
Why does a stray empty paragraph appear after a div inside a p?
Tips
Name foster parenting and paragraph closing, and say what each moves or creates.
Add that nested interactive content is a separate accessibility problem.
157.html-css-0157Mediummid
How do innerHTML, insertAdjacentHTML and DOMParser differ, and what happens to scripts and context?
innerHTML replaces all children and parses in the context of the element, insertAdjacentHTML adds markup at a position without touching existing nodes, and DOMParser builds a separate inert document. Scripts do not run through innerHTML, but event handler attributes do, so untrusted markup stays dangerous.
Full answer
Three APIs turn a string into DOM nodes. They differ in where the nodes go and in what the parser is allowed to do.
el.innerHTML = html replaces all children of el. The string is parsed in the context of that element, so the rules depend on it. A tr assigned to a div is dropped, because a div is not a place where rows are allowed. Scripts inserted this way do not run, but event handler attributes such as onerror do run. That is why innerHTML with untrusted text is dangerous. Replacing all children also removes event listeners that were on the old nodes, and it parses the whole string again each time.
el.insertAdjacentHTML(position, html) parses the string and adds it at one of four places without touching the existing children: beforebegin, afterbegin, beforeend and afterend. It is the right tool to append markup, and it does not rebuild the old content, so listeners on the existing nodes stay.
new DOMParser().parseFromString(html, "text/html") makes a separate, inert document. Nothing in it runs. Images do not load and scripts do not execute. You can read it with querySelector, for example to pull a fragment from a server response. Then you import the nodes you want with document.importNode. This is a good way to inspect markup safely, but the result is not safe to insert unless the content is sanitized.
Related: a template element holds parsed, inert content for later cloning, and createContextualFragment parses in a given context and does run scripts.
The new element is added after the old one, and the old one is untouched. The row string is dropped when parsed inside a div, but it stays when parsed inside a tbody. The script string did not run. The parsed document gave back the text of its b element.
Use textContent when the data is plain text, and a sanitizer when it is real markup from outside.
Checked in Chrome 156 only. The unsafe case is run on purpose in a test page. Never do this with real user data. 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
innerHTML replaces children and drops their listeners.
insertAdjacentHTML appends at four positions.
DOMParser makes an inert document.
Parsing depends on the context element.
Handler attributes still run; sanitize untrusted markup.
Common mistakes
Using innerHTML to append items in a loop, which re-parses and removes listeners.
Expecting a tr string to work when assigned to a div.
Treating a DOMParser result as safe to insert without sanitizing.
Follow-ups
Why does a tr string disappear when assigned to a div?
When would you use a template instead?
Tips
Explain the difference in where nodes go and what is replaced.
Say that scripts do not run through innerHTML but handler attributes do.
158.html-css-0158Easyfresher
Why is disabled="false" still disabled, and what are the rules for quoting attribute values?
A boolean attribute is on when present, whatever its value, so disabled="false" is still disabled. Remove the attribute or set the property to false. Quote values that contain spaces or special characters, and note that the first duplicate attribute wins.
Full answer
A boolean attribute is on when it is present and off when it is absent. The value does not matter. <input disabled>, <input disabled=""> and <input disabled="false"> are all disabled. The only way to turn it off is to remove the attribute. This is a common bug when a template writes disabled="{{ flag }}" and the flag is false.
In JavaScript, use the property: input.disabled = false removes the attribute, and input.disabled = true adds it. The same holds for checked, required, hidden, readonly, open, selected, multiple, autofocus and controls. Note that checked as an attribute sets the default state, while the property is the live state after the user clicks.
Quoting rules:
A value needs quotes when it has spaces, quotes, an equals sign, or angle brackets. class=a b gives the class a and a separate attribute named b.
Quotes can be double or single. Use the other kind inside the value, or write ".
Unquoted values are legal when they are simple, but a quoted style is safer and easier to read.
Attribute names and element names are not case sensitive in HTML. Values can be, for example type="text" is not case sensitive, but id and class values are.
If an attribute appears twice, the first one is used and the later ones are ignored.
Some attributes look boolean but are not. contenteditable, draggable, spellcheck and aria-hidden take the values true or false, and aria-hidden="false" is meaningful.
The first input is disabled even though the value says false. The div gets the class big and a separate attribute named small. The input with two value attributes shows the first one. The last div shows that draggable and aria-hidden read their values as text.
Use the property in scripts, and use frameworks' boolean bindings and not strings.
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
Boolean attributes depend on presence, not value.
Use the property in scripts: el.disabled = false.
Quote values with spaces or special characters.
The first duplicate attribute wins.
draggable and aria-hidden take true or false.
Common mistakes
Writing disabled="false" to enable a control.
Leaving out quotes around a class value with a space.
Treating aria-hidden or draggable as boolean attributes.
Follow-ups
How do you turn a boolean attribute off in a script?
What happens when an attribute is written twice?
Tips
State the rule: present means on, absent means off.
Mention the property versus attribute difference for checked.
Mojibake means text was written in one encoding and read in another, typically UTF-8 read as Windows-1252. The browser uses a byte order mark, then the Content-Type header, then meta charset. Make the file, header, meta tag and data all use UTF-8.
The charset parameter of the Content-Type header sent by the server.
A meta charset tag in the first part of the file (the first 1024 bytes).
A guess, which can be wrong.
The header wins over the meta tag. So a server that sends text/html; charset=iso-8859-1 overrides a correct meta charset="utf-8", and a missing header with a meta tag placed late in the head can also fail.
Debug steps:
Open the network panel and look at the Content-Type header of the page.
In the page, read document.characterSet to see what the browser decided.
Check how the file is saved in the editor, and fix the setting.
Check data that comes from a database, an API or a form: each hop must use UTF-8, including the connection and the table collation.
Put <meta charset="utf-8"> first in the head, and make the server send UTF-8 in the header.
The fix is always to make every part agree, not to replace the characters with entities.
Repeated damage cannot be undone by changing the encoding, so fix the source and the data.
html
<p id="out"></p>
<script>
const bytes = new TextEncoder().encode("é");
const wrong = new TextDecoder("windows-1252").decode(bytes);
const right = new TextDecoder("utf-8").decode(bytes);
window.result = { bytes: Array.from(bytes), wrong, right, set: document.characterSet };
out.textContent = wrong + " " + right;
</script>
The garbled text was produced on purpose by decoding bytes with the wrong encoding. The test did not use a real server or real response headers. 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.
Order: byte order mark, header, meta charset, guess.
The header overrides the meta tag.
Check document.characterSet and the network panel.
Every hop of the data must use UTF-8.
Common mistakes
Adding a meta charset tag when the server header says something else.
Fixing the display with entities and leaving wrong bytes in the database.
Placing the meta charset tag far down the head.
Follow-ups
Which wins, the Content-Type header or the meta tag?
How can a script read the encoding the browser used?
Tips
Show the two bytes example for é, and the order the browser uses to decide.
Say that the header wins over the meta tag.
160.html-css-0160Mediummid
How does contenteditable work, and why is building an editor on it harder than it looks?
contenteditable lets the user edit an element, with no value property and no change event, so read the content and listen to input. It needs a role and a name, browsers differ in the markup they create, and pasted content must be cleaned. Use input or textarea for plain text.
Full answer
The contenteditable attribute makes an element editable by the user, with caret, selection, undo and typing support from the browser. Values are true (or empty), false, and plaintext-only, which allows editing but keeps the content as plain text. The isContentEditable property tells if an element is editable, including through inheritance.
It is useful for small things: an inline title that can be edited, a notes box, or a rich text area. Facts to know:
The element is focusable, so it is in the tab order. Give it a role and a name, such as role="textbox", aria-multiline="true" and aria-label, or connect a visible label with aria-labelledby. A bare div has no meaning for a screen reader.
There is no value and no change event. Read innerText or textContent, or innerHTML for markup, and listen to input events.
Browsers produce different HTML for the same action. Pressing Enter may add a div, a p or a br. Pasting brings in styles and markup from other pages.
Pasted content is a security risk: it can include unwanted markup. Intercept the paste event and insert plain text, or sanitize the result.
The old document.execCommand API for bold and italic is deprecated, and there is no complete replacement. Real editors, such as those built on ProseMirror or similar libraries, keep their own document model and only use the editable element for input.
A form does not submit its content. Copy it into a hidden field or send it with a script.
For plain text fields, an input or textarea is simpler, more accessible and works with forms.
Typing into the first box fires input events and the text appears in it. The second box accepts only plain text. The first box is reachable by the keyboard and announced as a text box with the name "Notes".
The paste handler uses execCommand("insertText"), which still works for this purpose in current browsers, but check the support before relying on it.
Checked with real key presses in Chrome. No screen reader was run, and touch input 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
Values: true, false and plaintext-only.
Give it role=textbox and an accessible name.
Use the input event; there is no value or change.
Pasted markup is a risk; handle paste.
Prefer input and textarea for plain text.
Common mistakes
Using contenteditable for a simple text field instead of an input or textarea.
Forgetting a role and an accessible name.
Accepting pasted HTML from other pages without cleaning it.
Follow-ups
What does plaintext-only change?
Why is execCommand a poor base for a rich text editor?
Tips
State where it fits and where input or textarea is better.
Mention paste, Enter behaviour and the missing value and change event.