devsetswww.devsets.com/en/topics/layout/notes
HTML & CSS quick reference for interviews
The essentials of the topic on a couple of pages: key concepts by section and the pitfalls interviewers like to ask about.
HTML document and semantics
- Document base.
<!DOCTYPE html>turns on standards mode; without it the browser falls back to quirks mode.<html lang="en">helps screen readers, hyphenation and translation. Without<meta name="viewport" content="width=device-width, initial-scale=1">phones render the page about 980px wide and zoom out.- Semantic elements.
header,nav,main,article,section,aside,footerdescribe the role of a part of the page and become landmarks for screen readers. A page has one visiblemain.articleis self-contained content,sectionis a thematic group with a heading.- Headings.
h1-h6build the page outline that screen reader users navigate by. Don't skip levels and don't pick a level for its size: size is set in CSS.- Block and inline.
divis a block: it takes the full width and starts a new line.spanis inline: it ignoreswidth,heightand vertical margins.inline-blockflows with text but accepts sizes.- Meaning, not look.
strongandemmark importance and stress,bandionly change the look.awithhrefnavigates,buttonperforms an action.tableis for tabular data,dlfor term and description pairs,figurewithfigcaptionfor an illustration with a caption.- Attributes.
idis unique on the page,classcan repeat.data-user-idis read in JavaScript asel.dataset.userId. A block element likedivinsidepis invalid: the parser closespbefore it.
Forms
- label.
<label for="email">linked to the field'sid, or wrapping the field: a click focuses the field and screen readers read its name.placeholderis not a label: it disappears while typing and usually has low contrast.- Buttons.
- Inside a form a
<button>defaults totype="submit". Any other button needstype="button", or it submits the form. - Sending data.
GETputs fields into the URL query string,POSTinto the request body. An unchecked checkbox isn't sent at all. Fields withoutnamearen't sent either.- Groups.
- Radio buttons of one question share a
nameand are wrapped infieldsetwith alegendthat names the question. - Validation.
required,type="email",pattern,minandmaxare checked by the browser.:user-invalidhighlights errors only after the user has interacted, unlike:invalid, which fires on an empty form at once.- Errors.
- The message is linked to the field with
aria-describedby, and the field getsaria-invalid="true". Then a screen reader reads the error together with the field.
Box model
- Box.
- Content,
padding,border,margin. Padding is inside the border and gets the background, margin is outside and stays transparent. - box-sizing.
- With
border-box,widthincludes padding and border, so a 200px block stays 200px. The common reset sets it on*, *::before, *::after. - Margin collapsing.
- Adjacent vertical margins of blocks merge into the larger one: 20px and 30px give 30px, not 50px. A parent and its first child collapse too if the parent has no padding, border or its own BFC. Flex and grid items never collapse.
- Shorthands.
margin: 10px 20pxis vertical then horizontal. Four values go clockwise from the top: top, right, bottom, left.- overflow.
autoshows scrollbars only when needed,scrollalways.hiddenclips but the box can still be scrolled by script;clipclips without creating a scroll container, sostickyinside keeps working.- BFC.
- A block formatting context contains floats and stops margins collapsing through it. The clean way to create one is
display: flow-root;overflowother thanvisible, flex and grid items also create one. - Centering a block.
- A block with a width is centered with
margin-inline: auto.text-align: centercenters only inline content inside the block.
Cascade, specificity and inheritance
- Cascade order.
- First origin and
!important, then cascade layers, then specificity, then source order: the later rule wins. Inlinestylebeats any selector,!importantin a stylesheet beats inlinestyle. - Specificity.
- Counted as (ids, classes + attributes + pseudo-classes, types + pseudo-elements) and compared left to right.
#nav ais (1,0,1) and beats.menu .item a.linkat (0,3,1). - :is, :not, :has, :where.
:is(),:not()and:has()take the specificity of their most specific argument.:where()always adds zero, which makes it good for base styles that are easy to override.- Inheritance.
- Text properties are inherited:
color,font-*,line-height,visibility. Box properties are not:margin,border,background,width. - initial, inherit, unset.
initialis the value from the spec, not the browser default.inherittakes the parent's value.unsetacts asinheritfor inherited properties and asinitialfor the rest.- @layer.
- Among normal styles, a later declared layer beats an earlier one regardless of specificity, and styles outside any layer beat all layers. Putting resets and libraries into early layers removes specificity wars.
- Combinators.
.menu amatches any descendant,.menu > aonly direct children,h2 + pthe paragraph right afterh2,h2 ~ pall following sibling paragraphs.
@layer reset, vendor, components;
@import url("datepicker.css") layer(vendor);
@layer components {
.button { padding: 0.5rem 1rem; }
}
/* outside layers: wins over all of them */
.button.danger { background: crimson; }Positioning and stacking
- relative.
- Shifts the element visually, but its original place in the flow stays reserved. It also becomes the reference for absolutely positioned children.
- absolute.
- Taken out of the flow and positioned against the nearest ancestor whose
positionisn'tstatic.inset: 0stretches it over that ancestor. - fixed.
- Positioned against the viewport. An ancestor with
transform,filterorperspectivebecomes its containing block, and the element scrolls with that ancestor. - sticky.
- Behaves like
relativeuntil it reaches thetopoffset, then sticks inside its parent. It doesn't stick if an ancestor hasoverflow: hiddenorauto, or if the parent is no taller than the element. - z-index.
- Works on positioned elements and on flex and grid items. Values are compared only within one stacking context.
- Stacking context.
- Created by positioned elements with
z-index,opacitybelow 1,transform,filter,will-changeandisolation: isolate. A child withz-index: 9999can't rise above a neighbor of its parent's context.isolation: isolateon a component root keeps its layers inside.
Flexbox
- Axes.
justify-contentaligns along the main axis set byflex-direction,align-itemsalong the cross axis. Inflex-direction: column,justify-content: centercenters vertically.- flex: 1.
- Expands to
flex: 1 1 0%: grow, shrink, basis 0. Items share the free space equally regardless of content. In a row,flex-basistakes priority overwidth. - Spacing.
gapsets space between items without extra space after the last one.flex-wrap: wrapmoves items that don't fit to the next line.margin-left: autopushes an item and everything after it to the right.- Equal height.
- By default
align-items: stretchmakes items in a row as tall as the tallest one. - min-width: auto.
- A flex item doesn't shrink below its content, so a long word or
text-overflow: ellipsisstretches the row.min-width: 0on the item fixes it.flex-shrink: 0keeps an icon from being squeezed. - order.
- Changes only the visual order. Keyboard focus and screen readers follow the DOM, so a big mismatch confuses users.
.center {
display: flex;
justify-content: center;
align-items: center;
}
.navbar { display: flex; gap: 1rem; }
.navbar .logout { margin-left: auto; }
.row-item { flex: 1; min-width: 0; }
.row-item .title {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}Grid
- Tracks.
grid-template-columns: repeat(3, 1fr)gives three equal columns;fris a share of the free space.250px 1fris a fixed sidebar and content filling the rest.- Placement.
grid-column: 1 / -1stretches an item across all columns.grid-template-areasnames regions, and items take them withgrid-area.- auto-fill and auto-fit.
- With
minmax(200px, 1fr)both fit as many columns as possible.auto-fillkeeps empty tracks,auto-fitcollapses them, so a few items stretch to the full width. - Implicit grid.
- Items beyond the defined tracks create new rows automatically. Their size is set by
grid-auto-rows.grid-auto-flow: densefills gaps, but the visual order can then differ from the DOM. - Alignment.
place-items: centerisalign-itemsandjustify-itemsin one: each item is centered in its cell.- subgrid.
grid-template-rows: subgridlets a nested grid use the parent's tracks, so titles, text and buttons of neighboring cards line up.- Grid or Flexbox.
- Grid lays out in two dimensions by a predefined scheme: page layout, card grids. Flexbox lays out a single row or column by content size: toolbars, button groups.
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1rem;
}
.page {
display: grid;
grid-template-columns: 250px 1fr;
grid-template-areas: "side main";
}Units and responsive design
- em and rem.
remis relative to the root font size,emto the element's own font size (to the parent's forfont-sizeitself), soemcompounds in nested elements.%is relative to the containing block.- Viewport units.
50vwis half the viewport width. On phones100vhincludes the area under the browser bars: use100dvh, orsvhandlvhfor the smallest and largest heights.- clamp().
clamp(1rem, 2.5vw, 2rem)on a 1000px screen is 25px, within 16-32px. Fluid type with arempart, likeclamp(1rem, 0.9rem + 1vw, 1.5rem), still follows the user's font size.- Media queries.
- Mobile first: base styles for small screens,
@media (min-width: 48em)adds more. The range syntax@media (width >= 768px)is shorter. Breakpoints inemfollow the user's font settings. - Container queries.
container-type: inline-sizeon the parent and@container (min-width: 400px)on the component: it adapts to the space it's placed in, not to the screen.cqiis 1% of the container's width.- User preferences.
@media (hover: hover)for hover effects only on devices with a mouse,prefers-reduced-motionto turn off animations,prefers-color-schemefor the dark theme.- Logical properties.
margin-inline-start,padding-block,inset-inline-endfollow the writing direction, so an RTL layout (Arabic, Hebrew) mirrors without separate styles.
.grid { display: grid; gap: 1rem; }
@media (width >= 48em) {
.grid { grid-template-columns: 1fr 1fr; }
}
.card-wrap { container-type: inline-size; }
@container (min-width: 400px) {
.card { display: flex; }
}Images and media
- Base rule.
img { max-width: 100%; height: auto; }keeps images inside the container without distorting them.- srcset and sizes.
srcsetlists files of different widths,sizestells how wide the image will be on screen. The browser picks the file for the screen and pixel density.- picture.
- Needed for art direction (a different crop on phones) or for formats with a fallback:
sourcewith AVIF or WebP, then a JPEGimg. - Loading.
loading="lazy"defers images below the fold. The main hero image getsfetchpriority="high"instead and isn't lazy.- Sizing.
object-fit: coverfills the box and crops the rest,object-position: topchooses which part stays.aspect-ratio: 16 / 9keeps the proportions of a video container.- Gap under img.
- An image is inline and sits on the text baseline, leaving space for descenders.
display: blockorvertical-align: middleremoves it. - img or background.
- Content images go in
imgwithalt: they're indexed and read aloud. Decorative backgrounds and patterns go inbackground-image.
Modern CSS
- Custom properties.
--brand: #4f46e5andcolor: var(--brand, black). Unlike Sass$variables, they exist at runtime: they inherit through the DOM, change in media queries and from JavaScript.- :has().
- A parent selector:
.card:has(img)is a card containing an image,.field:has(input:invalid)a field with an error.:focus-withinmatches an element with focus inside. - Nesting.
- Native nesting with
&works without a preprocessor:.card { &:hover { ... } .title { ... } }. - Colors.
oklch()has perceptually even lightness, so a palette of shades is easy to build.color-mix(in oklch, var(--brand) 80%, white)mixes colors.#3366ff80has 80 as alpha, about 50%.- Themes.
color-scheme: light darkswitches form controls and scrollbars.light-dark(#111, #eee)picks a value for the current scheme.currentColorreuses the text color for borders and icons.- Feature checks.
@supports (display: grid)applies styles only where the property is supported.@propertydeclares a typed variable that can be animated.- New building blocks.
- The
popoverattribute and<dialog>give top-layer popups,@starting-styleanimates appearance fromdisplay: none, View Transitions animate between states, anchor positioning attaches a tooltip to its trigger,text-wrap: balanceevens out heading lines.
Tailwind CSS
- Utility-first.
- Styles are built from small classes right in the markup:
flex,p-4,text-sm. No class names to invent and no dead CSS. The spacing step is0.25rem, sop-4is1rem. - Variants.
md:flexapplies from themdbreakpoint up (mobile first).hover:,focus-visible:,disabled:.dark:followsprefers-color-schemeby default in v4.- group and peer.
groupon a parent andgroup-hover:on a child style the child when the parent is hovered.peerandpeer-checked:style an element by the state of its sibling.data-[state=open]:styles by a data attribute.- Arbitrary values.
w-[37px],bg-[#1da1f2],grid-cols-[200px_1fr]for values outside the theme.- Full class names.
- Tailwind finds classes by scanning source files as text, so
bg-${color}-500isn't generated. Keep full names in a map:{ red: "bg-red-500" }. - v4.
- Configured in CSS:
@import "tailwindcss"and@theme { --color-brand: ... }createbg-brand,text-brandand so on. Sources are detected automatically. A class-based dark theme:@custom-variant dark (&:where(.dark, .dark *)). - Merging classes.
- When a component takes outside classes, conflicts like
p-2andp-4are resolved bytailwind-merge.@applyis for rare cases like third-party markup, otherwise it brings back the problems of plain CSS.
Accessibility
- Native first.
button,a,label,dialogalready have a role, focus and keyboard handling. ARIA is for cases with no native element. Adivwithrole="button"also needstabindex="0"and Enter and Space handlers.- Focus.
:focus-visibleshows the ring for keyboard users and not on mouse clicks. Never removeoutlinewithout a replacement.tabindex="0"adds an element to the tab order,-1makes it focusable only from script, positive values break the order.- Hiding.
display: nonehides from everyone.aria-hidden="true"hides only from screen readers: for decorative icons. Asr-onlyclass hides visually but keeps the text for screen readers.- alt.
- A decorative image gets an empty
alt="". An icon-only link describes its destination:alt="Home", notalt="house icon".aria-labelis for controls with no visible text. - WCAG.
- Level AA is the usual target: 4.5:1 contrast for normal text, 3:1 for large text, targets at least 24 by 24 px (WCAG 2.2). A is the minimum, AAA the strictest.
- Dialogs and SPAs.
dialog.showModal()traps focus, closes on Esc and makes the rest of the pageinert. After navigation in an SPA, move focus to the new heading or announce the change witharia-live.- Landmarks and skip link.
header,nav,main,footerlet screen reader users jump between regions. A skip link at the start of the page moves keyboard focus straight tomain.
.sr-only {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}Rendering and performance
- Pipeline.
- Style, layout, paint, composite. Changing
widthorleftgoes through all steps;transformandopacityneed only compositing, so they animate smoothly at 60 FPS. - Layout thrashing.
- Reading
offsetHeightorgetBoundingClientRect()right after changing styles forces a synchronous layout. In a loop it repeats every time: read everything first, then write. - Hints.
will-change: transformonly right before an animation and on a few elements: each one takes memory.contain: contentandcontent-visibility: autolet the browser skip work for isolated or offscreen parts.- Core Web Vitals.
- LCP (loading the main content), INP (response to input), CLS (layout shifts). Lighthouse gives lab data from one run, CrUX and RUM give field data from real users.
- Avoiding CLS.
widthandheightoraspect-ratioon images and embeds, reserved space for banners,font-display: swapwith a fallback font tuned bysize-adjust.- CSS delivery.
- Critical CSS for the first screen is inlined, the rest loads normally.
@importinside CSS loads files one after another. Content hashes in file names (app.3f9a1c.css) allow long caching. - Scripts and hints.
deferruns scripts in order after parsing,asyncruns each as soon as it loads.preloadfetches a resource for the current page with high priority,prefetchone for the next page at low priority.
Common pitfalls
outline: nonewithout a replacement focus style leaves keyboard users without a visible focus.z-index: 9999doesn't help if the parent hastransformoropacity: they create a stacking context.position: stickydoesn't stick under an ancestor withoverflow: hiddenorauto.position: fixedinside an element withtransformis positioned against that element, not the viewport.- A long word or
text-overflow: ellipsisin a flex item stretches the row: addmin-width: 0to the item. height: 100vhon phones is taller than the visible area: use100dvh.- A
<button>inside a form withouttypesubmits the form. ::beforeand::afterdon't render withoutcontent, even an emptycontent: "". They don't work onimgandinputat all.widthandheighton an inline element likespanhave no effect.- Tailwind doesn't generate classes built from strings:
bg-${color}-500never reaches the CSS. transition: allalso animates properties you didn't plan to, including expensive layout ones.placeholderinstead oflabel: the hint disappears while typing and screen readers may not read it as the field's name.