Questions 181–193 of 193 · 0 of 13 on this page marked learned
181.html-css-0181Easyfresher
What does noscript do, and what does progressive enhancement mean for a page?
noscript holds content for when scripting is off. Progressive enhancement starts with HTML that works for everyone, then adds CSS and JavaScript as improvements. Real links and forms work first, and a js class lets CSS adapt only when scripts run.
Full answer
The noscript element holds content that is used only when scripting is off or not supported. When scripts are on, the browser does not render it. It is allowed in the head (with link, style and meta) and in the body. Typical uses: a message such as "This page works better with JavaScript", a plain stylesheet link, or a fallback image for a script-driven tag.
Progressive enhancement is the idea behind it. Start with HTML that works for everyone, and add CSS and JavaScript as improvements for browsers that support them.
HTML first: the content, links and forms work with no styles and no scripts. A form posts to the server, a link goes to a real address, and a menu is a list of links.
CSS next: layout and appearance improve the page.
JavaScript last: enhances the page, for example with validation messages, a menu button, or loading content without a page reload.
Reasons: scripts can fail to load because of a bad network, an error, a blocker or a slow device. Search engines and tools may read the HTML first. People with old browsers or assistive tools may not support a feature. Even users who have scripts on pass through a moment before they run.
Patterns:
Use a js class on the html element, set by a small script in the head, so CSS can hide things that need scripts only when scripts will run.
Do not hide content with a script-only reveal that can never appear if the script fails.
Build links and buttons as real links and buttons that work first, and enhance them.
Scripts are on in this test, so the js class is added and the script-only paragraph is shown. The noscript content is not rendered, and a script sees it as plain text. The form works with no script at all, because it has an action and a method.
Test the page with scripts turned off to see what users get then.
html
<style>
.js-only { display: none; }
.js .js-only { display: block; }
</style>
<script>document.documentElement.classList.add("js");</script>
<p class="js-only" id="j">Shown only when scripts run.</p>
<noscript id="ns"><p>Please turn on JavaScript for the live preview.</p></noscript>
<form id="f" action="/subscribe" method="post"><label for="e">Email</label> <input id="e" name="email" type="email"> <button type="submit">Join</button></form>
Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
noscript content shows only when scripting is off.
Start with working HTML, then CSS, then JavaScript.
Forms and links should work without scripts.
A js class on html lets CSS adapt.
Test with scripts blocked.
Common mistakes
Building a page that shows nothing without JavaScript when plain HTML would do.
Using links with href="#" and click handlers instead of real addresses.
Never testing with scripts blocked.
Follow-ups
Where is noscript allowed?
Why add a js class to the html element?
Tips
Define the layers: HTML, CSS, JavaScript, and say why that order.
Give the form example that works without scripts.
182.html-css-0182Easyfresher
How do you write links for downloads, email addresses and phone numbers?
The protocol in href decides the action: mailto: for email with optional subject, tel: for phone numbers in international format, and normal addresses for pages. The download attribute saves same-origin files with a suggested name. Link text should be clear and say when a link opens a file or a new tab.
Full answer
An a element can point to more than a web page. The protocol at the start of href tells the browser what to do.
A normal page link uses https:, a relative path or a fragment such as #section.
mailto: opens the mail program. mailto:hello@example.com?subject=Hello can add a subject, and values must be URL-encoded. Several addresses are separated by commas.
tel: starts a phone call on phones and some desktop apps. Write the number with the country code and no spaces: tel:+911234567890. The visible text can be written for readers with spaces.
sms: opens a text message on phones, and its support differs by device.
download tells the browser to save the target as a file and not open it. A value gives the suggested file name: download="report.pdf". It works only for same-origin addresses (and for blob: and data: addresses). For a file from another site, the browser may ignore it and just navigate.
href="#" links to the top of the page and is not a good button. Use a button for actions.
Other useful attributes:
target="_blank" opens a new tab. Warn users when links open a new tab, and add rel="noopener" if you target older browsers.
hreflang and type give hints about the target. ping is not widely supported.
For file links, show the file type and size in the text: "Syllabus (PDF, 240 KB)". This helps people on slow connections and people using screen readers.
Links must have clear text. "Click here" says nothing when links are listed by a screen reader. Use "Download the syllabus" instead.
The first link downloads a file with the suggested name. The second opens a new email with the subject filled in. The third offers a call on devices that support it. The last opens a new tab and says so in its text.
Test these links on a phone and a desktop, because what happens depends on the device and the installed apps.
html
<ul>
<li><a id="dl" href="/files/syllabus.pdf" download="syllabus.pdf">Download the syllabus (PDF)</a></li>
<li><a id="mail" href="mailto:hello@example.com?subject=Course%20question">Email us</a></li>
<li><a id="tel" href="tel:+911234567890">+91 12345 67890</a></li>
<li><a id="ext" href="https://example.org" target="_blank" rel="noopener">External site (opens in a new tab)</a></li>
</ul>
The check read the link properties. Opening a mail program, making a call and saving a file depend on the device and 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
mailto: and tel: open the mail and phone apps.
Write phone numbers in international format without spaces.
download works for same-origin addresses.
Use buttons for actions, not href="#".
Link text should be clear and mention files and new tabs.
Common mistakes
Using href="#" with a click handler instead of a button.
Writing phone numbers with spaces or no country code in the href.
Expecting the download attribute to work for another site's file.
Follow-ups
When does the download attribute work?
Why include the file type and size in the link text?
Tips
List the schemes and one point for each.
Mention link text that works out of context.
183.html-css-0183Easyfresher
What do cursor, pointer-events and user-select do, and what are their limits for accessibility?
cursor changes the pointer shape, pointer-events: none lets clicks pass through an element, and user-select: none prevents text selection. None of them change keyboard or screen reader behaviour, so use the disabled attribute or inert to switch off a control, and avoid blocking selection of real content.
Full answer
These three properties change how the mouse interacts with an element.
cursor changes the mouse pointer shape: pointer (a hand) for clickable things, not-allowed for disabled controls, text over text, grab for draggable items. It is only a visual hint for mouse users. It does not make an element clickable.
pointer-events: none makes an element ignore the mouse, so clicks, hovers and taps pass through to the element underneath. This helps with decorative overlays, such as a gradient on top of a scrolling list, and with children inside a button. pointer-events: auto brings it back, and it is inherited, so a child can turn it on again.
user-select: none stops the user from selecting text by mouse. It suits buttons and drag handles, where selection is a nuisance. Do not use it on content, because people copy text, and it hurts accessibility tools and users who select text to read it.
Limits and traps:
pointer-events: none does not remove an element from the keyboard. A button with it can still be focused with Tab and activated with Enter. It also does not hide it from screen readers. To disable a control for everyone, use the disabled attribute (or inert), and not only CSS.
A disabled button does not fire click events, and some browsers also stop hover events on it, which can break tooltips.
A custom cursor: pointer on a non-interactive element suggests a click that does nothing. Use it only for real controls.
On touch screens there is no cursor, so never depend on it to show what is clickable. Make the shape and the text clear.
The overlay covers the button but ignores the mouse, so the button underneath still receives clicks. The user-select: none text cannot be selected by dragging. The button shows a hand cursor when it is enabled. The last button has pointer-events: none, so the mouse ignores it, but Tab still focuses it and Enter still activates it.
Use disabled, not CSS alone, to switch a control off.
Checked with a mouse click and real key presses in Chrome. Touch 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
cursor is a visual hint only.
pointer-events: none lets clicks pass through.
user-select: none blocks text selection.
pointer-events: none does not stop keyboard activation.
Use disabled or inert to disable controls.
Common mistakes
Using pointer-events: none to disable a control and leaving it focusable by keyboard.
Applying user-select: none to article text.
Using cursor: pointer on things that are not clickable.
Follow-ups
How can a child element receive clicks inside a parent with pointer-events: none?
How do you disable a button properly?
Tips
Say what each property does and what it does not do.
State that pointer-events: none is not a way to disable a control.
184.html-css-0184Easyfresher
What are attribute selectors, and when do you use the forms with ^=, $=, *=, ~= and |=?
Attribute selectors match by presence or by value: exact, starts with (^=), ends with ($=), contains (*=), word in a list (~=) and language prefix (|=). They have class specificity. An i flag ignores case, and the matching works on the attribute text, so relative links differ from absolute ones.
Full answer
An attribute selector matches elements by an attribute or by its value. It has the same specificity as a class, which is (0,1,0).
The forms:
[disabled] matches when the attribute is present, whatever the value.
[type="email"] matches when the value is exactly email.
[href^="https"] matches when the value starts with the text. Use it for secure links, or for links that start with /docs.
[href$=".pdf"] matches when the value ends with the text. Use it for file types.
[href*="@"] matches when the value contains the text anywhere.
[class~="btn-lg"] matches when the value is a space-separated list that contains the word. This is how a class selector works inside.
[lang|="en"] matches en or any value that starts with en-, such as en-GB.
Add a space and i before the closing bracket, for example [href$=".pdf" i], to ignore case. The attribute name is not case-sensitive in HTML, and values of some attributes, such as type, are already case-insensitive.
Good uses: styling form inputs by type, marking external or file links, styling ARIA states such as [aria-expanded="true"], and styling data attributes. Be careful with these:
Quotes are needed when the value has special characters or spaces. Using them every time is a good habit.
*= can match more than you expect. [class*="btn"] also matches my-btn-group and btnx.
A selector on href sees the attribute text, not the full resolved address. A relative link /files/a.pdf does not start with https.
Attribute selectors are not faster or slower in a way that matters on normal pages, but a very broad one, such as [class], can match many elements.
The secure link is green, the PDF link is red, and the mail link is purple. The upper-case file is italic, because the rule with the i flag matches it, but it stays the default blue, because the first PDF rule is case-sensitive and does not match. The disabled input is half transparent, the British English paragraph is teal, and the big button has a 24 pixel font.
Pick the simplest selector that is clear. A class is often better than a long attribute selector.
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
[attr] checks presence; [attr="v"] checks the exact value.
^=, $= and *= match start, end and contains.
~= matches a word in a list; |= matches a language prefix.
Specificity is the same as a class.
Add i to ignore case.
Common mistakes
Using *= when ^= or $= is exact enough, and matching too much.
Expecting [href^="https"] to match a relative link.
Forgetting the i flag for upper-case file extensions.
Follow-ups
What does [lang|="en"] match?
How do you match a value case-insensitively?
Tips
Name the operators in a table-like list with one use each.
Say that the specificity equals a class.
185.html-css-0185Easyfresher
What is the difference between GET and POST in a form, and what do action and enctype do?
GET puts the data in the address and suits searches that change nothing. POST sends the data in the body and suits changes, private data and files. action is the target address, and enctype must be multipart/form-data for file uploads. Only named, enabled fields are sent.
Full answer
A form sends its fields to a server. Three attributes control how.
action is the address that receives the data. If it is missing, the form sends to the current page address.
method is get or post. If it is missing, the default is get.
enctype is the format of the body for post. The default is application/x-www-form-urlencoded. Use multipart/form-data when the form has a file input. text/plain exists, but it is for testing.
GET puts the data in the address, as in /search?q=hello+world. Use it for reading and searching, where the request does not change anything on the server. The address can be bookmarked, shared and cached, and the back button works well. Do not use it for passwords or private data, because addresses are stored in the history, in server logs and in referrer headers. Addresses also have a length limit.
POST puts the data in the body of the request. Use it when the request creates or changes something, such as signing up, paying or posting a comment, and for private data and for files. A POST request is not stored in the address bar and not bookmarked. After a POST, the server should answer with a redirect to a new page (the post/redirect/get pattern), so that reloading the page does not send the form a second time.
Neither method is safe on its own. Private data needs HTTPS in both cases, and POST forms that change data need protection against cross-site request forgery, for example a token. Also, validate on the server, because the browser checks can be skipped.
Only fields with a name are sent. Unchecked checkboxes and disabled fields are not sent.
The first form creates the address /search?q=hello+world. The second form sends the file in a multipart body. The third form has no method, so it uses get, and the default encoding is the URL-encoded format.
Choose the method by what the request does, and not by how the address looks.
The check read the form properties and the data that the form would send. No server received a request. 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
action is the target; the default method is get.
GET data is in the address; use it for searching.
POST data is in the body; use it for changes and files.
Files need enctype="multipart/form-data".
Only fields with a name are sent.
Common mistakes
Sending passwords with GET.
Forgetting enctype="multipart/form-data" on a form with a file input.
Forgetting the name attribute, so the field is not sent.
Follow-ups
What is the default method of a form?
What is the post/redirect/get pattern?
Tips
Link the method to the meaning: GET reads, POST changes.
Mention that hiding data in POST is not security by itself.
186.html-css-0186Easyfresher
What is the difference between opacity and a transparent background colour?
A colour with alpha makes only that colour see-through. opacity fades the whole element with its children as one group and creates a stacking context. An element with opacity 0 is still in the layout, clickable and focusable.
Full answer
Both make things see-through, but they work on different parts of an element.
A colour with alpha, such as rgb(0 0 0 / 50%) or rgba(0, 0, 0, 0.5), affects only that colour. Text and borders keep their own colours. Children are not changed.
opacity affects the whole element as one group: its background, border, text and all its children. The value goes from 0 (invisible) to 1 (normal). Children cannot be more opaque than their parent.
Use alpha when you want a see-through background with clear text, for example a dark overlay behind white text. Use opacity when you want to fade the whole element, for example in a fade animation or for a disabled look.
More points:
opacity is not inherited, but its effect covers the children anyway, because the element is drawn as one group.
opacity below 1 creates a new stacking context. This can change how z-index works for the children, and it can trap a positioned child so it cannot appear above outside elements.
An element with opacity: 0 is still in the layout, it still receives clicks and keyboard focus, and screen readers still read it. It is not a way to hide content. Use display: none, hidden or inert for that.
Transitions of opacity are cheap for the browser, because they usually do not need layout or repaint.
Low contrast: faded text can fail the contrast rules. Check the final colours, because opacity mixes the text with the background.
In the first box, only the background is half transparent, and the white text stays fully white. In the second box, the background, the text and everything inside are half transparent, so the text looks dimmer. The text element has its own opacity of 1, but it is still faded, because its parent is drawn as a group.
Decide first what should fade, and then pick the tool.
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
Alpha colour affects only that colour.
opacity affects the whole element and its children.
opacity below 1 creates a stacking context.
opacity: 0 does not hide the element from keyboard or screen readers.
Check the contrast of the final result.
Common mistakes
Using opacity on a container when only the background should be see-through.
Using opacity: 0 to hide content and leaving it focusable.
Forgetting that opacity creates a stacking context.
Follow-ups
Does opacity: 0 remove an element from the layout?
Why can opacity change z-index behaviour?
Tips
Say which parts each property affects.
Give one example for each: overlay and fade.
187.html-css-0187Easyfresher
How do line-height, letter-spacing and line length affect readable text, and how does line-height inherit?
Use a line height of about 1.5, a line length of about 65 characters with the ch unit, relative font sizes and small letter spacing only for labels. A unitless line-height is inherited as a number, while lengths and percentages are inherited as calculated lengths.
Full answer
Good body text needs enough space between lines, a sensible line length and a comfortable size.
line-height is the height of each line box. A value from about 1.4 to 1.6 works well for body text. Long lines and small text need more space, headings need less (for example 1.1 to 1.3).
letter-spacing adds space between letters. Use small values in em, so the spacing scales with the font size. A little extra space helps small upper-case labels. Do not add spacing to body text, and never use it on joined scripts such as Arabic, where it breaks the letter connections.
Line length, also called measure: about 45 to 75 characters per line reads well. Use max-width in ch units, for example max-width: 65ch, so the width follows the font.
Font size: use relative units such as rem, so users can change the size in the browser. At least 16 pixels for body text is a common base.
Contrast and alignment: left-aligned text is easier to read than justified text with no hyphenation, and very long paragraphs need breaks.
The important detail is how line-height inherits:
A unitless number, such as 1.5, is inherited as the number. Every child multiplies it by its own font size. This is the best choice.
A length, such as 30px, or a percentage, such as 150%, or em, is calculated once on the parent, and children inherit the final length. A small child text then gets the same large line height, which can cause uneven spacing.
WCAG text spacing rules also ask that content keeps working when users set a line height of 1.5 and extra letter and word spacing, so avoid fixed heights on text boxes.
The small text under the unitless value gets 15 pixels, which is 1.5 times its own size. Under the fixed length and the percentage, it keeps 30 pixels, which is too large for the small text. The label has 1 pixel of letter spacing at 20 pixels.
Test the text in real languages and sizes, and with the user's own zoom settings.
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
Body text: line-height about 1.4 to 1.6.
Use a unitless line-height so children scale it.
Limit line length to about 45 to 75 characters (ch units).
Use letter-spacing in em, and only where needed.
Avoid fixed heights on text boxes.
Common mistakes
Using px or % line-height on a parent and getting tall lines in small children.
Adding letter-spacing to body text or to Arabic text.
Using very long lines with no max-width.
Follow-ups
Why is a unitless line-height better?
Why avoid letter-spacing in Arabic?
Tips
Explain the unitless line-height rule with the three examples.
Give numbers: 1.4 to 1.6 for body, 45 to 75 characters per line.
188.html-css-0188Easyfresher
How do you create a simple grid with columns, rows, gaps and items that span more than one cell?
Set display: grid on the parent, define columns with grid-template-columns using fixed sizes and fr units, add gap, and let rows form automatically. Items span tracks with grid-column or grid-row, and lines are numbered from 1.
Full answer
CSS Grid places items in rows and columns. You turn it on for the parent, and the children become grid items.
Basic steps:
display: grid on the container.
Define the columns with grid-template-columns. For example 100px 1fr 2fr makes three columns. The fr unit is a share of the free space. After the fixed 100 pixels, the second column gets one share and the third gets two shares.
Rows are made automatically as needed. Their size is auto by default. Set grid-template-rows or grid-auto-rows to control them.
gap sets the space between rows and columns. It only adds space between tracks, not at the outer edges.
repeat(3, 1fr) is a short way to write three equal columns.
Items are placed in order. To make an item bigger, use grid-column: span 2, or give start and end lines, such as grid-column: 1 / 3. Lines are numbered from 1.
Use Grid when you plan rows and columns together, for example a card list, a gallery or a page layout. Use Flexbox when you lay out items in one line or one direction. They also work together.
Useful extras: align-items and justify-items align items inside their cells. minmax(0, 1fr) stops long content from stretching a column. The browser tools show grid lines and track sizes, which helps when learning.
The first grid has widths of 100, 160 and 320 pixels. The free space is 600 minus 100 minus 20 for the two gaps, which is 480 pixels, shared as one part and two parts. The fourth item wraps into a second row. In the second grid, the wide item takes two of three equal columns, the next item fills the last column of the first row, and the third item moves to the second row.
Draw the rows and columns on paper first, and then write the template.
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
display: grid makes children grid items.
fr is a share of the free space after fixed sizes and gaps.
gap adds space between tracks only.
repeat() shortens repeated tracks.
span or line numbers place larger items.
Common mistakes
Using margins for spacing between items instead of gap.
Thinking that fr includes the fixed columns and the gaps.
Counting grid lines from 0.
Follow-ups
What is the difference between 1fr and auto?
How do you make an item span two rows?
Tips
Describe the three steps: display grid, columns, gap.
Explain fr as a share of the free space after fixed sizes and gaps.
189.html-css-0189Easyfresher
How does vertical-align work, and why does it not centre a block element?
vertical-align works on inline-level elements and table cells, not on block elements. It aligns an inline box inside its line, with baseline as the default, which causes the gap under images. To centre blocks, use Flexbox or Grid.
Full answer
vertical-align works in two places only: on inline-level elements, and on table cells. It does not work on normal block elements such as a div. This is the most common mistake, and it is why people say "vertical-align does not work".
On inline and inline-block elements, it aligns the element inside its line:
baseline is the default. The bottom of an inline-block box sits on the text baseline, so there is a small gap below it for letters like "g" and "y".
top and bottom align the box with the top or bottom of the line.
middle aligns the middle of the box with the middle of the lower-case letters in the parent text.
text-top, text-bottom, sub and super align by the font or shift the box.
A length or a percentage raises or lowers the box.
On table cells (td, th and elements with display: table-cell), it aligns the content inside the cell: top, middle or bottom. The default for cells is middle.
The baseline gap is a common cause of strange space under images. An image is inline by default and sits on the baseline. Setting vertical-align: middle or display: block on the image removes the gap.
To centre a block, use Flexbox or Grid instead: display: flex; align-items: center;, or display: grid; place-items: center;. These are the current tools. Older code used display: table-cell with vertical-align: middle.
The box on the baseline stays above the bottom of the line. The top box touches the top of the line box, and the bottom box touches the bottom. In the table cell, the text is in the middle. The div inside the tall wrapper stays at the top, because vertical-align does nothing on a block.
For a modern centred layout, choose Flexbox or Grid, and keep vertical-align for inline icons and table cells.
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
Works on inline-level elements and table cells only.
baseline is the default, and it leaves a gap for descenders.
top, middle and bottom align in the line or the cell.
It does nothing on block elements.
Use flex or grid to centre blocks.
Common mistakes
Using vertical-align on a div and expecting it to centre.
Ignoring the baseline gap under inline images.
Using table-cell tricks for new layouts.
Follow-ups
Why is there a gap under an inline image?
What is the default value of vertical-align?
Tips
State where vertical-align works: inline and table cells only.
Name the modern way to centre a block: flex or grid.
190.html-css-0190Easyfresher
What are the ways to add CSS to a page, and which one should you choose?
Use an external stylesheet through link for most sites because it is cached and shared. Internal style elements suit small or critical CSS, inline styles suit dynamic values, and @import creates a slower chain, though it can place a file into a layer.
Full answer
There are four ways to add CSS.
External file with <link rel="stylesheet" href="site.css"> in the head. This is the normal choice. The browser downloads it once, caches it, and shares it between pages. Several pages stay consistent with one change.
Internal <style> element in the head. It is useful for small pages, for a small amount of critical CSS, and for HTML emails and examples. The styles cannot be cached apart from the page.
Inline style="..." attribute on one element. It has very high specificity, so it is hard to override from a stylesheet, and it cannot use selectors such as :hover or media queries. It is handy for values set by a script, such as a custom property or a position. Some content security policies block inline styles.
@import url("more.css") inside CSS. It loads another stylesheet, but the browser finds it only after the first file is downloaded, so the files load one after the other. This slows rendering. Prefer several link elements, or combine files in a build step. Note that @import also lets you place a file into a layer, for example @import url("vendor.css") layer(vendor).
CSS blocks rendering. The browser waits for stylesheets in the head before it paints, to avoid a flash of unstyled content. This is a reason to keep files small and to avoid long chains.
Order matters. When two rules have equal specificity, the later one wins, and this includes the order of link and style elements in the page.
Other tips:
Use media on a link for files that apply only in some cases, such as media="print".
Keep inline styles for values that really are dynamic.
Cache static CSS files with a long lifetime and versioned file names.
The site.css file in this example sets .late { color: rgb(1, 2, 3); }. The class rule is more specific than p, so the first paragraph uses it. The inline style wins on the second paragraph, and the third paragraph uses the internal p rule.
Choose external files for the site, and use the other forms only where they are the better tool.
html
<link rel="stylesheet" href="/css/site.css">
<style>
p { color: red; }
</style>
<p class="late" id="a">External class wins over the internal element rule</p>
<p id="b" style="color: blue">Inline style</p>
<p id="c">Internal style</p>
Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
External files are cached and shared.
A style element suits small pages and critical CSS.
Inline styles have high specificity and no selectors.
@import files load in a chain, one after the other.
CSS blocks rendering, and order matters.
Common mistakes
Using @import chains in production CSS.
Putting styles inline everywhere, and then using !important to override them.
Putting the stylesheet link at the end of the page, so users see unstyled content first.
Follow-ups
Why is @import slower than a link element?
When is an inline style a good choice?
Tips
List the four ways, with one reason for or against each.
Mention render blocking and caching.
191.html-css-0191Easyfresher
How does the browser handle spaces and line breaks in HTML, and what does the white-space property change?
HTML collapses runs of spaces and line breaks into one space. The white-space property changes this: nowrap stops wrapping, pre keeps everything, pre-wrap keeps spaces and wraps, and pre-line keeps only line breaks. makes a non-breaking space that does not collapse.
Full answer
In normal HTML text, the browser collapses white space. Several spaces, tabs and line breaks in the source become a single space on screen. Spaces at the start and end of a line are removed. This lets you format your HTML source freely.
The white-space property changes the rules:
normal: collapse spaces and wrap lines. This is the default.
nowrap: collapse spaces, but never wrap. The text can overflow its box. Use it for short labels and with text-overflow: ellipsis.
pre: keep spaces and line breaks, and do not wrap. This is what the pre element uses, and it suits code.
pre-wrap: keep spaces and line breaks, but wrap long lines. It suits text from a textarea.
pre-line: collapse spaces, keep line breaks, and wrap. It suits text with simple line breaks.
break-spaces: like pre-wrap, but trailing spaces take up space and can wrap.
Other points:
Inline elements next to each other with a space or line break between them show a small gap on screen, because that space is real. If the tags touch with no space, there is no gap. Flexbox and Grid ignore this space between items.
For a space that must not collapse and must not break, use , for example between a number and its unit, "10 km". Use CSS spacing for layout, and not repeated .
A br element forces a line break. Use it in addresses and poems, and not to add vertical space. Use margins for that.
innerText shows the text as rendered, and textContent returns the raw source text.
The first paragraph reads as One two three. The pre element keeps its spaces. The third paragraph keeps its line break, so it is two lines high. The nowrap paragraph overflows its box. The two spaces in the last paragraph stay, because they are non-breaking. The spans with a space between them have a gap, and the spans without one touch.
When the page shows the wrong spacing, check the white-space rule before changing the layout.
html
<style>
.t { line-height: 20px; width: 200px; margin: 0; }
.nw { white-space: nowrap; width: 100px; overflow: hidden; }
</style>
<p class="t" id="a">One two
three</p>
<pre class="t" id="b"> keep this</pre>
<p class="t" id="c" style="white-space: pre-line">line1
line2</p>
<p class="t nw" id="d">A very long label that does not wrap</p>
<p class="t" id="e">x y</p>
<span id="s1">a</span> <span id="s2">b</span><br>
<span id="s3">a</span><span id="s4">b</span>
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
Spaces and line breaks collapse into one space by default.
nowrap stops wrapping; pre keeps everything.
pre-wrap and pre-line keep user line breaks and wrap.
does not collapse or break.
A space between inline elements is a real gap.
Common mistakes
Using many entities to indent text.
Using br tags for vertical spacing.
Wondering about gaps between inline-block elements without remembering the space in the source.
Follow-ups
Why is there a gap between two inline-block buttons?
What is the difference between pre-wrap and pre-line?
Tips
Say what collapsing means before listing the property values.
Mention pre-wrap and pre-line for user text.
192.html-css-0192Easyfresher
How do you mark and style the current page in a navigation menu so that everyone can tell where they are?
Mark the link of the current page with aria-current="page" and style that attribute with more than colour. It works for assistive technology and keeps the style tied to the meaning. Set it on the server if possible, and keep one current link in a list.
Full answer
Users need to know which page they are on. Two things are needed: a visual sign and a sign for assistive technology.
For the meaning, use aria-current. The value page marks the link that points to the current page. A screen reader announces it as "current page". Other values exist: step for a step in a process, location for a place in a map or flow, date and time, and true as a general value. Do not use the current class alone, because a class has no meaning for a screen reader.
For the look, style the attribute: a[aria-current="page"] { ... }. This keeps the style and the meaning in one place, so they cannot get out of step. Use more than colour alone to show the state, such as a bold weight, an underline or a border. Colour alone fails for users with colour vision problems.
Other points:
Put the menu in a nav element, with a label such as aria-label="Main" if the page has more than one nav.
The current page can still be a link. Some sites remove the link, but a working link is simple and predictable.
Set the attribute on the server when the HTML is built. This works without JavaScript and is ready on first paint. A script can do it for static sites, by comparing a.pathname with location.pathname, and it must also run on client-side navigation.
Only one link in a list should have aria-current="page". For a section with sub-pages, mark the current page, and style the parent as the active section with a different class.
The script marks the link whose path matches the current page. The CSS then shows it in bold with a bottom border. A screen reader announces the link as the current page. The script is a fallback for static files, and a server-built menu is better when you have one.
Test with a screen reader to hear how it announces the current link.
html
<style>
nav a { color: #234; text-decoration: none; padding: 4px 8px; display: inline-block; }
nav a[aria-current="page"] { font-weight: 700; border-bottom: 2px solid currentcolor; }
</style>
<nav aria-label="Main">
<ul>
<li><a id="home" href="/index.html">Home</a></li>
<li><a id="courses" href="/courses">Courses</a></li>
</ul>
</nav>
<script>
for (const a of document.querySelectorAll("nav a")) {
if (a.pathname === location.pathname) a.setAttribute("aria-current", "page");
}
</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
aria-current="page" marks the current link.
Style a[aria-current] so meaning and look stay together.
Use more than colour to show the state.
Put the menu in a labelled nav.
Set it on the server when possible.
Common mistakes
Using only a CSS class, so assistive technology gets no information.
Showing the current page by colour alone.
Marking several links as the current page.
Follow-ups
What is the difference between aria-current="page" and aria-selected?
Why add a text sign besides colour?
Tips
Say that meaning and style come from the same attribute.
Name the values: page, step, location.
193.html-css-0193Mediummid
What does display: contents do, when is it useful, and what are the risks?
display: contents removes the element's own box so its children take part in the parent's layout. It is useful to let wrappers join a grid or flex layout. Semantic elements can lose their roles in some browsers, so test before using it on them.
Full answer
display: contents removes the box of an element from the layout, but keeps its children. The children are laid out as if they were direct children of the element's parent. The element itself has no background, border, padding or size, because it has no box. Its inherited properties, such as colour and font, still reach the children.
Main use: let wrapper elements take part in a Grid or Flexbox layout of an ancestor. For example, markup groups three cards inside a div for the code structure, but the design needs all cards in one grid. With display: contents on the wrapper, the cards become grid items of the grid parent. Other uses are a form or fieldset wrapper around items in a layout, and removing a helper wrapper in a component whose markup you cannot change.
Risks:
Accessibility: browsers have had bugs where elements with display: contents lost their role or were removed from the accessibility tree, including button, table and list elements. Fixes arrived in many browsers, but support differs across browsers and screen readers. Do not use it on interactive or semantic elements without testing with the tools your users have.
The element with no box cannot be used for spacing, a background or a border, and position and transform on it have no effect.
It is easy to forget which element is the grid item. Use the browser tools to check.
Alternatives: subgrid when the wrapper has its own box but its children should follow the parent's tracks, or changing the markup, or a wrapper-free layout with CSS Grid placement.
In the first grid, the three items sit in three columns, one next to the other, because the wrapper has no box. In the second grid, the wrapper is a normal block, so it is one grid item in the first column and the items are stacked inside it.
Use it for structure that has no meaning, and test semantic elements before you rely on it.
Checked in Chrome 156 only, by reading the item positions. Screen readers were not run, so the accessibility notes come from the known support differences, not from this test. 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 element has no box, but its children stay.
Children join the grandparent's grid or flex layout.
Background, border, padding and size are ignored.
Accessibility support has been uneven for semantic elements.
Consider subgrid or changing the markup.
Common mistakes
Using display: contents on buttons, lists or tables and not testing assistive technology.
Expecting a background or padding on the element.
Using it when subgrid would keep the box and the alignment.
Follow-ups
What is the difference between display: contents and subgrid?
Why does a background not work on it?
Tips
Explain it as removing the box but keeping the children.
State the accessibility risk with semantic elements.