HTML & CSS Middle cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. What is the specificity of the selector
nav#main .item:hover > a::before?Correct answer: (1, 2, 3) - an ID, class + pseudo-class, two types + pseudo-element
Count by column: IDs -
#main(1); classes, attributes and pseudo-classes -.itemand:hover(2); types and pseudo-elements -nav,a,::before(3). Combinators (>, space) add no specificity. A pseudo-class weighs like a class, and a pseudo-element like a type selector.2. How do you override a third-party library's
!importantrule without touching its code?Correct answer: Write your own rule also with
!importantand a more specific selectorA normal rule never beats
!important, however specific it is. Among several!importantdeclarations, specificity and order apply again. Other options: an inline style with!important, or cascade layers - for!importantthe layer order is reversed. The best path is avoiding!importantin your own code.3. What does the shorthand
flex: 1expand to?Correct answer:
flex-grow: 1; flex-shrink: 1; flex-basis: 0%flex: 1=1 1 0%: the base size is zero, so all space is split strictly in proportion toflex-grow- columns end up equal regardless of content.flex: auto=1 1 auto- only the free space beyond content size is shared.flex: none=0 0 auto.4. How does
flex-basisdiffer fromwidthon a flex item in a row (flex-direction: row)?Correct answer:
flex-basisis the initial main-axis size; if it isn'tauto, it takes precedence overwidthflex-basissets the item's initial size along the main axis, from whichgrowandshrinkare computed. Withflex-basis: auto,widthis used (orheightin a column). Withflex-direction: column,flex-basisapplies to height rather than width - that's the key difference fromwidth.5. Inside a flex item, long text with
text-overflow: ellipsisdoesn't truncate and stretches the column instead. How do you fix it?Correct answer: Give the flex item
min-width: 0(oroverflow: hidden)Flex items have
min-width: autoby default - they won't shrink below their minimum content. A long word or awhite-space: nowrapline stretches the item.min-width: 0allows shrinking, and thenellipsiskicks in.flex-shrink: 0would only make it worse.6. How does
repeat(auto-fill, minmax(200px, 1fr))differ fromrepeat(auto-fit, minmax(200px, 1fr))?Correct answer:
auto-fillkeeps empty columns, whileauto-fitcollapses them and stretches the itemsBoth create as many columns as fit. The difference shows when there are fewer items than slots:
auto-fillkeeps the empty tracks, whileauto-fitcollapses them to zero and1frstretches the existing items. For cards that should fill the row,auto-fitis the usual choice.7. How do you define a "header on top, sidebar and content in the middle, footer at the bottom" layout in Grid with named areas?
Correct answer: With
grid-template-areason the container andgrid-areaon the childrengrid-template-areasdescribes the layout as string "pictures":"header header" "sidebar main" "footer footer", and items attach viagrid-area: header. A dot.marks an empty cell. It's great for responsiveness: a media query only changes the template. There is nogrid-area-namesproperty.8. What is an implicit grid?
Correct answer: Tracks the browser creates automatically for items that don't fit the explicit grid
The explicit grid is defined by
grid-template-*. If there are more items than cells, the browser adds implicit tracks sized bygrid-auto-rows/grid-auto-columns, with auto-placement direction set bygrid-auto-flow. By default implicit rows areauto-sized.9. What does
place-items: centerdo on a grid container?Correct answer: Shorthand for
align-items+justify-items: centers items within their cellsplace-items=align-items+justify-items, i.e. aligning each item within its own cell. Aligning the whole grid (tracks) within the container isplace-content(align-content+justify-content). The container itself is centered by its parent's styles.10. When is Grid more appropriate, and when Flexbox?
Correct answer: Grid for two dimensions, Flexbox for one
Flexbox arranges items along a single axis and suits "content defines size": menus, toolbars, alignment within a component. Grid controls both axes at once and suits "layout defines size": page layouts, galleries. Both are current and often used together.
11. What does
font-size: clamp(1rem, 2.5vw, 2rem)resolve to on a 1000px-wide screen (1rem = 16px)?Correct answer: 25px
clamp(MIN, VAL, MAX)returns VAL bounded below by MIN and above by MAX. 2.5vw at 1000px = 25px, which is between 16px and 32px, so the result is 25px. At 400px it would be 10px → clamped to 16px; at 2000px → 50px → clamped to 32px. This gives fluid typography without media queries.12. Why use logical properties like
margin-inline-startinstead ofmargin-left?Correct answer: They adapt automatically to the writing direction (RTL, vertical text)
Logical properties follow the text direction:
inlineis the line axis,blockis the block axis,start/endare the beginning and end. In Arabic (RTL),margin-inline-startends up on the right without extra styles. Shorthands exist too:padding-inline,inset-block,inline-size. They don't affect performance.13. How does
transitiondiffer fromanimation?Correct answer:
transitionis a change between two states,animationis a@keyframessequenceA transition needs a trigger - a value change (
:hover, class change) - and knows only the start and end. An animation is described with keyframes; it can start immediately, repeat (animation-iteration-count), run in reverse and pause (animation-play-state).14. Which properties are best to animate for smooth 60 FPS?
Correct answer:
transformandopacitytransformandopacityare usually handled at the compositing stage and don't trigger layout or paint. Animatingwidth,topormarginforces the browser to recalculate layout every frame, causing jank. That's why you move things withtranslate, notleft.15. Why is
transform: translate()often better than changinglefton aposition: absoluteelement for movement animations?Correct answer:
translatedoesn't change layout, whileleftrecalculates layout every frameMoving via
transformdoesn't affect flow or trigger reflow, so the animation is smoother.leftcan be animated, but it's more expensive. Both support percentages, but they're computed differently:translateuses the element's own size (hence thetranslate(-50%, -50%)centering trick),leftuses the containing block.16. How should
will-changebe used?Correct answer: Sparingly - on elements about to animate, removing it afterwards
will-changehints the browser to prepare a layer in advance. Used broadly, it eats memory (each layer is a separate texture) and can slow the page down. It's a last resort for a specific performance problem, not a replacement fortransition.17. What is Critical CSS?
Correct answer: Above-the-fold styles inlined in
<head>; the rest loads laterExternal CSS blocks rendering: the browser won't paint until the styles download. Inlining the above-the-fold styles in the HTML and loading the rest asynchronously makes the first paint (FCP/LCP) happen sooner. The downside is duplicated styles and a more complex build.
18. What does the CLS (Cumulative Layout Shift) metric measure?
Correct answer: Unexpected layout shifts during the page's lifetime
CLS measures visual stability: how much content "jumps". A good value is under 0.1. Time to the largest element is LCP, responsiveness is INP. The main causes of shifts are images without dimensions, banners and ads without reserved space, and web fonts.
19. Which technique best prevents layout shifts caused by loading images?
Correct answer: Set
widthandheight(oraspect-ratio) to reserve the spaceKnowing the proportions, the browser reserves space before the file loads, so content doesn't jump. Modern browsers compute
aspect-ratiofrom thewidth/heightattributes automatically. Lazy loading without dimensions makes shifts worse, and loading via JS hurts LCP.20. What does
font-display: swapdo in@font-face?Correct answer: Shows text in a fallback font immediately and swaps in the web font once loaded
swapremoves "invisible text" (FOIT): users see content in a fallback font right away, then the font changes (FOUT). This can cause a small layout shift, reduced by tuning fallback metrics (size-adjust). Theoptionalvalue lets the browser skip the font entirely on a slow network.21. What are the
srcsetandsizesattributes on<img>for?Correct answer: So the browser picks a file of the right size
srcsetlists file variants (img-400.jpg 400w, img-800.jpg 800w), andsizeshints how wide the image will be in the layout ((max-width: 600px) 100vw, 50vw). The browser downloads the smallest sufficient file. To change cropping or format, use<picture>.22. When do you need
<picture>rather than just<img srcset>?Correct answer: When you need to switch formats (AVIF/WebP with a fallback) or cropping
<picture>with multiple<source>elements enables art direction (different cropping on mobile viamedia) and format selection (type="image/avif"), while the inner<img>is the fallback and carriesalt. For a simple resolution switch,srcset/sizeson<img>is enough.23. What does
loading="lazy"on<img>do, and when should you NOT use it?Correct answer: Defers loading until the image nears the viewport; avoid it on the LCP image
Native lazy loading saves bandwidth for below-the-fold images. But for a hero image it's harmful: the browser starts loading later and LCP suffers. For an important image, use
fetchpriority="high"instead. The attribute has nothing to do with compression or formats.24. What does
object-fit: coverdo on an<img>with setwidthandheight?Correct answer: Keeps proportions and fills the whole box, cropping the excess
coverfills the entire area, keeps the proportions and crops what sticks out (the focal point is set withobject-position). Fitting the whole image with bars iscontain. Distorting proportions is the default behavior (fill).25. What is the specificity of
:where(.card, #hero) p?Correct answer: (0, 0, 1) -
:where()always contributes zero specificity:where()zeroes out the specificity of its arguments, leaving onlyp- (0,0,1). That's handy for base styles in libraries: they are easy to override. Its sibling:is()takes the specificity of its most specific argument -:is(.card, #hero) pwould be (1,0,1).26. What does the selector
.card:has(img)match?Correct answer: Cards that contain at least one
<img>image:has()is the "parent selector": it matches an element if something inside it (or next to it, with+and~combinators) matches the argument. The card itself is styled, not the image. Examples:form:has(:invalid),label:has(+ input:checked). Attributes are selected with[attr].27. How do CSS variables (
--x) fundamentally differ from Sass variables ($x)?Correct answer:
--xlives in the browser and changes at runtime, while$xis substituted at build timeA Sass variable is a compile-time value; it doesn't exist in the output CSS. A custom property takes part in the cascade: it can be overridden per component, in
@media, on:hover, in a dark theme, or from JavaScript viastyle.setProperty. They're usually combined: Sass for build logic, CSS variables for themes and dynamics.28. What is a stacking context, and why might
z-index: 9999"not work"?Correct answer: A group within which
z-indexvalues compare; a child can't rise above its parent's siblingsAn element with
position+z-index,opacity < 1,transform,filter,isolation: isolateand so on creates its own stacking context. Everything inside it is painted as a single unit relative to its siblings. If a parent withz-index: 1is below a sibling withz-index: 2, a child with9999still ends up below that sibling.29.
position: stickyisn't working even thoughtop: 0is set. What's the most likely cause?Correct answer: One of the ancestors has
overflow: hidden,autoorscrollA sticky element sticks to its nearest scrolling ancestor. If an ancestor's
overflowisn'tvisible, sticky is measured against it, and that ancestor may not scroll at all - visually nothing happens. Another cause: the parent is no taller than the element, so there's nowhere to stick. To clip without creating a scroll container, useoverflow: clip.30. What is a block formatting context (BFC), and how do you create one?
Correct answer: An isolated layout region, e.g. via
display: flow-rootA BFC is an isolated layout region: it contains its floats (doesn't collapse in height) and prevents children's margins from collapsing with the parent's. It's created by
display: flow-root(the modern way),overflowother thanvisible, flex/grid items,position: absolute, etc. It used to be the clearfix technique.31. What's new about the
@media (width >= 768px)syntax?Correct answer: It's the range syntax from Media Queries Level 4, equivalent to
min-widthRange syntax allows comparisons:
(width >= 768px),(400px <= width < 1000px). It's shorter and avoidsmin/maxconfusion at the boundaries. All modern browsers support it, and Tailwind v4 generates breakpoints in this form. Container queries are written with@container.32. What are
@containercontainer queries for?Correct answer: To style a component by its container's size
Media queries look at the viewport, but a component may sit in a narrow sidebar or a wide column. Container queries let a card adapt to its actual space: the parent gets
container-type: inline-size, and styles use@container (width > 400px) { ... }.@mediais not deprecated.33. Why can
height: 100vhbe taller than the visible area on mobile, and how do you fix it?Correct answer:
vhignores the address bar; thedvh,svh,lvhunits helpMobile browsers compute
100vhfrom the maximum height (with the toolbar hidden), so the bottom of the block hides under the address bar. The new units:svh- smallest viewport height,lvh- largest,dvh- dynamic, changing along with the toolbar.34. What does the
currentColorvalue mean?Correct answer: The value of the current element's
colorpropertycurrentColorsubstitutes the computedcolorvalue. It's handy for SVG icons (fill: currentColor), borders and shadows that should match the text color: changecoloron:hover, and the icon recolors along with the text.35. How do the
initial,inheritandunsetvalues differ?Correct answer: Spec value, parent's value, or either one by property
initialtakes the value from the CSS specification (fordisplaythat'sinline, not the browser'sblockfordiv). Browser-style values are restored byrevert.inherittakes the parent's computed value.unsetacts as the "natural" value: inherited properties inherit, others reset toinitial.36. In BEM, how do you correctly name the title class inside a
cardblock in its "accent" variant?Correct answer:
card__title card__title--accentBEM: block (
card), element with two underscores (card__title), modifier with two dashes (card__title--accent). The modifier goes together with the base class so base styles aren't duplicated. A flat class structure gives low, uniform specificity and a predictable cascade.37. How do CSS Modules solve class-name collisions?
Correct answer: They generate unique class names, making styles local to the file
The
.titleclass fromCard.module.cssbecomes something likeCard_title__x7a2b, and the component imports a mapping object. Collisions disappear without naming conventions. Global styles use:global. Shadow DOM is a Web Components mechanism; CSS Modules don't use it.38. Why is
:focus-visiblebetter than:focusfor styling the focus outline?Correct answer: It shows the outline mainly for keyboard users
Designers used to ask to remove the "ugly" ring after a click, and
outline: nonebroke keyboard accessibility.:focus-visibleuses a browser heuristic: during keyboard navigation the outline is visible, on a mouse click on a button it usually isn't. Never remove focus indication entirely.39. What does
tabindex="-1"do?Correct answer: Allows focus only programmatically (
el.focus()), not via Tabtabindex="0"adds an element to the natural tab order, while-1makes it focusable only via JS (e.g. a modal heading or a container when following an anchor). Positive values change the tab order and are considered an anti-pattern. To remove an element from interaction entirely, use theinertattribute.40. When is
aria-labeljustified?Correct answer: When an interactive element has no visible text, like an icon button
aria-labelsets an element's accessible name when there's no visible label:<button aria-label="Close">✕</button>. The first rule of ARIA is not to use it when a native option exists:altfor images,<label>for fields.aria-labeldoesn't affect SEO, and an unnecessary one can override clear visible text.41. How do you apply an arbitrary value in Tailwind that isn't in the theme?
Correct answer:
w-[347px]Square brackets set an arbitrary value:
w-[347px],bg-[#1da1f2],grid-cols-[1fr_2fr](spaces become underscores). In v4, parentheses are shorthand for a CSS variable:w-(--sidebar-width)=width: var(--sidebar-width). If a value repeats often, move it into the theme.42. Why can't you build a Tailwind class name like `
bg-${color}-500`?Correct answer: The scanner only finds complete class names
Tailwind doesn't run your code; it statically scans files for class-like tokens. The string
bg-${color}-500doesn't contain a complete name, sobg-red-500isn't generated. The right way is mapping to full names:{ red: "bg-red-500", blue: "bg-blue-500" }[color].43. How do you add a custom
brandcolor in Tailwind v4 so thatbg-brand,text-brand, etc. work?Correct answer: Declare
--color-brandinside@themein CSSIn v4 configuration moved into CSS: variables in
@theme { --color-brand: oklch(...); }create both the utilities (bg-brand,border-brand) and a regular CSS variablevar(--color-brand). The oldtailwind.config.jsis supported via@configbut isn't needed by default.44. What are
groupandpeerfor in Tailwind?Correct answer: For styling based on a parent's state (
group-hover:) or a sibling's (peer-checked:)Put
groupon the parent and writegroup-hover:text-whiteon a descendant - the style applies when the parent is hovered.peerworks for following siblings:<input class="peer">+<p class="peer-invalid:visible">. Combining classes into one is@apply.45. A React component merges external classes:
className={"p-2 " + props.className}, and receivesp-4. What padding results?Correct answer: It depends on rule order in the CSS, not in
classClass order in the
classattribute doesn't affect the cascade: with equal specificity, the rule that comes later in the CSS file wins. So the outcome ofp-2 p-4is unpredictable from the component's point of view.tailwind-merge(often via acn()helper) removes conflicting classes and keeps the last one.46. What is Tailwind's
@applydirective for, and why shouldn't you overuse it?Correct answer: It inlines utilities into your own class
.btn { @apply px-4 py-2 rounded; }is handy for styling third-party HTML or base elements. But rewriting a whole project with@applygives you plain CSS with an extra abstraction layer and a bigger bundle. In Tailwind, reuse is usually solved with (React) components, not classes.47. How do you accommodate users for whom animations cause discomfort?
Correct answer: Use
prefers-reduced-motion: reduceto simplify or disable animationsUsers can enable "reduce motion" in their OS (vestibular disorders, migraines).
@media (prefers-reduced-motion: reduce)lets you replace parallax and large movements with gentle transitions. Tailwind hasmotion-reduce:andmotion-safe:variants for this.48. How do you build a two-column layout with a fixed-width sidebar and content filling the rest?
Correct answer:
display: grid; grid-template-columns: 250px 1fr250px 1fr- the first column is fixed, the second takes all the remaining space.100%in the second column would overflow the container by 250px. The Flexbox equivalent:flex: 0 0 250pxfor the sidebar,flex: 1for the content (and possiblymin-width: 0).49. Which image format usually gives the best compression for photos in modern browsers?
Correct answer: AVIF or WebP, with a JPEG fallback if needed
AVIF and WebP weigh noticeably less than JPEG at the same quality. Lossless PNG is for graphics with transparency and sharp edges, but it's huge for photos. BMP isn't compressed at all. SVG is better for icons and logos. Fallbacks are done with
<picture>or automatically by a CDN/optimizer (e.g.next/image).50. How do you properly include print-only styles?
Correct answer: A
media="print"attribute on<link>or an@media printblockmedia="print"and@media printapply styles only when printing: hide navigation and ads, remove backgrounds, show link URLs viaa::after { content: " (" attr(href) ")" }, control page breaks withbreak-inside: avoid.window.print()only opens the print dialog.51. What is the specificity of
:is(#hero, .card) p?Correct answer: (1, 0, 1) - it takes its most specific argument
That is the key difference from
:where(), which always contributes zero.:is(#hero, .card) pbeats.card peven when the element only matched via.card.52. What does
aspect-ratio: 16 / 9give you on a video container?Correct answer: The height follows the width, reserving space
It replaced the old
padding-top: 56.25%hack. Reserving space prevents layout shifts while iframes or images load.53. What does
inset: 0mean on an absolutely positioned overlay?Correct answer: All four offsets are 0, covering the block
insetis the shorthand for the four offsets and follows the same 1–4 value order asmargin. Combined withposition: absoluteand aposition: relativeparent it creates a full overlay.54. What does
grid-auto-flow: densedo?Correct answer: Fills earlier gaps with later smaller items
It is handy for galleries with items of different spans. Like
order, it can break the correspondence between visual and keyboard order.55. Why add
flex-shrink: 0to an icon inside a flex row with long text?Correct answer: So the icon isn't squeezed when space runs out
Flex items shrink by default (
flex-shrink: 1). Fixed-size elements like icons and avatars should opt out, while the text getsmin-width: 0to truncate.56. How do you push the last item of a flex navbar to the far right?
.nav { display: flex; } .nav .logout { margin-left: auto; }Correct answer: Give it
margin-left: autoIn flex layout auto margins take all remaining space in that direction.
margin-inline-start: autois the logical-property version that also works in RTL.57. What does
object-position: topdo withobject-fit: cover?Correct answer: Aligns the cropped image to the top
object-fitdecides how the image fills the box,object-positiondecides which part stays visible. The default is50% 50%, the center.58. What is
@supportsfor?@supports (display: grid) { .layout { display: grid; } }Correct answer: Applying styles if a CSS feature is supported
It checks feature support, not browsers.
@supports selector(:has(a))tests selectors too. Write a working fallback outside the block.59. How do you follow the user's system dark theme in plain CSS?
@media (prefers-color-scheme: dark) { :root { --bg: #111; --text: #eee; } }Correct answer: With the
prefers-color-schememedia featureIf the site also has a manual theme toggle, combine it with a class or
data-themeattribute that takes priority over the media query.60. What does
color-scheme: light darkon:rootdo?Correct answer: Native controls and scrollbars follow the theme
Without it, form fields and scrollbars stay light on a dark page. It doesn't recolor your own styles - that is still your CSS.
61. What is
accent-colorfor?Correct answer: Tinting native checkboxes and range sliders
It keeps native, accessible controls while matching the design - often enough instead of rebuilding a checkbox from scratch.
62. What does
.field:focus-withinmatch?Correct answer:
.fieldwhen it or a descendant has focusIt lets a wrapper highlight when its input is focused, or keeps a dropdown open while focus is inside it.
63. How do you change the color of list bullets without touching the text?
li::marker { color: tomato; }Correct answer: With the
::markerpseudo-element::markersupports a limited set of properties such ascolor,font-*andcontent. For fully custom bullets uselist-style: noneand::before.64. How can CSS number headings like "Step 1", "Step 2" automatically?
.steps { counter-reset: step; } .steps h3::before { counter-increment: step; content: "Step " counter(step) ": "; }Correct answer: With CSS counters and
counter()Counters update automatically when items are added or removed. Generated content in
::beforeisn't selectable and may not be announced consistently by screen readers, so don't put essential info there.65. How do you truncate text to three lines with an ellipsis?
.excerpt { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; overflow: hidden; }Correct answer: With
line-clamp, using-webkit-prefixestext-overflow: ellipsisworks only for a single line (withwhite-space: nowrapandoverflow: hidden). The prefixed line-clamp pattern is supported in all modern browsers.66. Why is there a small gap under an
<img>inside a<div>?Correct answer: Images are inline and sit on the text baseline
The space below the baseline is reserved for letters like "g" and "y". Most CSS resets set
img { display: block; }for this reason.67. What does
transform-originchange?.menu { transform: scale(0.95); transform-origin: top right; }Correct answer: The point around which rotations and scaling happen
By default it is the center. A dropdown opening from a top-right button looks natural when it scales from
top right.68. Why is
transition: all 0.3sconsidered a bad habit?Correct answer: It animates every property that changes
List the properties explicitly (
transition: transform 0.3s, opacity 0.3s). That keeps animations cheap and predictable.69. Why add
aria-hidden="true"to a decorative icon next to a button label?<button><svg aria-hidden="true">...</svg> Save</button>Correct answer: So screen readers skip the icon
Never put
aria-hiddenon focusable elements - keyboard users would reach something that screen readers can't describe.70. How do you make a screen reader announce "Saved" after an async action without moving focus?
<div aria-live="polite">{{ statusMessage }}</div>Correct answer: Use a live region that exists before the update
Screen readers watch live regions for changes. The region must already be in the DOM; inserting it together with the text is often missed. Use
assertiveonly for urgent errors.71. What is needed to make
<div role="button">behave like a real button?Correct answer:
tabindex="0"plus Enter and Space handlingARIA changes what assistive tech announces, not behavior. A
<button>is focusable, activates with keyboard and works with forms out of the box.72. How do you hide a text label visually but keep it for screen readers?
Correct answer: With a visually hidden (
sr-only) classdisplay: noneandvisibility: hiddenremove the content from the accessibility tree. Tailwind'ssr-onlyutility implements the clipping pattern.73. What
altshould an icon-only link to the home page have?<a href="/"><img src="logo.svg" alt="?" /></a>Correct answer: Text describing the destination, e.g. "Home"
When an image is the only content of a link, its
altbecomes the link's name. Describe what the link does, not what the image looks like.74. How do you style an element based on a
data-stateattribute in Tailwind?<div data-state="open" class="data-[state=open]:bg-zinc-100">...</div>Correct answer: With the
data-[...]variantHeadless UI libraries (Radix, Headless UI) expose state via
data-*and ARIA attributes, sodata-[state=open]:andaria-expanded:variants style them without extra classes.75. What does
srcset="logo.png 1x, logo@2x.png 2x"do?Correct answer: Picks a sharper image on high-density screens
Density (
x) descriptors suit fixed-size images like logos. For images whose size depends on the layout, use width (w) descriptors withsizes.