HTML & CSS Junior 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.

Quick reference: Key concepts and pitfalls on a couple of pages →
  1. 1. Why do HTML documents start with <!DOCTYPE html>?

    Correct answer: To enable standards rendering mode instead of quirks mode

    DOCTYPE is neither a tag nor a resource link. It tells the browser the page follows modern standards and switches on standards mode. Without it the browser falls back to quirks mode and emulates old browser bugs (for example, a different box model). The encoding is set by <meta charset="utf-8">, not by DOCTYPE.

  2. 2. Which set contains only HTML5 semantic elements?

    Correct answer: <header>, <nav>, <main>, <article>, <footer>

    Semantic elements describe the meaning of content: header, navigation, main content, a standalone article, footer. <div> and <span> are neutral containers with no meaning, while <b> and <i> are presentational (highlighting without importance). Semantics helps screen readers, search engines and code readability.

  3. 3. How many visible <main> elements can a page have, and what is it for?

    Correct answer: One - it holds the main unique content of the page

    <main> marks the main content of the document that is unique to the page (without header, menu and footer). Only one may be visible (others need the hidden attribute). It is a landmark for screen readers: users can jump straight to the content. <section> is a thematic section, not a replacement for <main>.

  4. 4. How does <div> differ from <span> by default?

    Correct answer: <div> is a block element, <span> is an inline element

    <div> has display: block by default: it stretches to the full width of its parent and starts on a new line. <span> has display: inline: it flows within text and is as wide as its content. Neither carries semantics - both are containers for grouping and styling.

  5. 5. You set width: 200px; height: 50px on a <span> with no other styles. What happens?

    Correct answer: Width and height are ignored because <span> is an inline element

    width and height don't apply to inline elements - their size is determined by content. Vertical margin doesn't push neighbors either. To size the element, it needs display: inline-block, block, or must be a flex/grid item.

  6. 6. How does display: inline-block differ from inline?

    Correct answer: inline-block stays in the line of text but accepts width, height and vertical spacing

    inline-block is a hybrid: on the outside it behaves like an inline element (sits on the same line as its neighbors and respects vertical-align), and on the inside like a block (width, height, padding and vertical margin work). It's block that starts on a new line, not inline-block.

  7. 7. How do you read the value of the data-user-id="42" attribute in JavaScript?

    Correct answer: element.dataset.userId

    All data-* attributes are available through element.dataset, with kebab-case names converted to camelCase: data-user-id → dataset.userId. The value is always a string. You can also use getAttribute('data-user-id'). In CSS they are accessed via the [data-user-id] selector and the attr() function.

  8. 8. What is the main difference between the id and class attributes?

    Correct answer: id must be unique on the page and has higher CSS specificity; class can repeat

    An id value must be unique in the document: anchors (#section), label for and ARIA attributes reference it. Classes are reused across many elements, and one element can have several. An id selector weighs (1,0,0) versus (0,1,0) for a class, which is why classes are usually preferred for styling.

  9. 9. Why add rel="noopener noreferrer" to a link with target="_blank"?

    Correct answer: So the opened tab doesn't get window.opener and the source page's address

    Without noopener, the new tab can use window.opener to replace the original page (reverse tabnabbing). noreferrer additionally omits the Referer header. Modern browsers already apply noopener to _blank by default, but the attribute is still written explicitly. Indexing is affected by nofollow, not these values.

  10. 10. What is the default type of a <button> inside a <form>?

    Correct answer: submit

    By default a button inside a form has type="submit" and submits the form. It's a common source of bugs: a "Show password" button suddenly submits the form. Buttons that shouldn't submit need an explicit type="button".

  11. 11. Why link a <label> to an <input> with for and id?

    Correct answer: Clicking the label focuses the field, and screen readers announce the label with it

    A linked label enlarges the clickable area (especially important for checkboxes) and gives the field an accessible name for assistive technologies. It doesn't affect submission or validation. The alternative is to wrap the input inside the label.

  12. 12. What alt should a purely decorative image (e.g. a divider ornament) have?

    Correct answer: An empty alt=""

    An empty alt="" tells screen readers the image is decorative and should be skipped. If alt is missing, a screen reader may read out the file name. Text like "image" is useless: alt should convey the image's meaning, not the fact that it exists.

  13. 13. What does box-sizing: border-box do?

    Correct answer: Includes padding and border in the specified width and height

    With content-box (the default), width sets only the content width, and padding and border are added on top: width: 200px + padding: 20px = 240px. With border-box, the total width is exactly 200px and the content shrinks. That's why many CSS resets apply border-box to every element. margin is never part of the size.

  14. 14. How does padding differ from margin?

    Correct answer: padding is inner spacing (painted with background), margin is outer spacing (always transparent)

    The box model order is content → padding → border → margin. padding sits inside the border and is painted with the element's background; margin is outside and transparent. Also, vertical margins of adjacent blocks can collapse while padding never does, and margin can be negative while padding cannot.

  15. 15. Two blocks are stacked. The top one has margin-bottom: 20px, the bottom one margin-top: 30px. What is the gap between them?

    Correct answer: 30px

    This is margin collapsing: of two adjacent vertical margins in normal flow, the larger one wins - 30px. Horizontal margins don't collapse, and there is no collapsing inside flex and grid containers at all.

  16. 16. Both selectors set color on the same link. Which wins: #nav a or .menu .item a.link?

    Correct answer: #nav a - a single ID outweighs any number of classes

    Specificity is compared column by column (IDs, classes/attributes/pseudo-classes, types): #nav a = (1,0,1), .menu .item a.link = (0,3,1). The first column matters most, so the ID wins. Source order only decides when specificity is equal.

  17. 17. Which of these properties is inherited by child elements by default?

    Correct answer: color

    Mostly text properties are inherited: color, font-*, line-height, text-align, visibility. Box model properties (border, padding, margin, width) and backgrounds are not. You can force inheritance with the inherit value.

  18. 18. How does display: none differ from visibility: hidden?

    Correct answer: display: none removes the element from layout; visibility: hidden hides it but keeps its space

    With display: none the element isn't rendered and takes no space - neighbors shift. With visibility: hidden it's invisible but its space remains. opacity: 0 also keeps the space, and the element stays clickable. None of these remove the element from the DOM, and screen readers ignore only the first two.

  19. 19. How does an element with position: relative; top: 10px behave?

    Correct answer: It shifts 10px down from its normal spot, but that spot in the flow is preserved

    relative visually shifts the element relative to where it would be in normal flow, but its space isn't released - neighbors don't move. relative is also often set on a parent to make it the reference point for absolutely positioned children. Positioning relative to the window is fixed.

  20. 20. What is an element with position: absolute positioned relative to?

    Correct answer: The nearest ancestor whose position is not static

    An absolute element leaves the flow and measures top/left/... from its containing block - the nearest positioned ancestor (relative, absolute, fixed, sticky). If there is none, it uses the initial containing block. That's why, to pin a close button to a card's corner, the card gets position: relative.

  21. 21. How does position: sticky; top: 0 work?

    Correct answer: The element stays in flow until scrolling reaches top: 0, then "sticks" - within its parent

    sticky is a hybrid of relative and fixed: before the threshold it's in flow, after it - pinned until its parent container ends. Common reasons sticky "doesn't work": no top is set, an ancestor has overflow: hidden/auto, or the parent is no taller than the element itself.

  22. 22. Which elements does z-index apply to?

    Correct answer: Positioned elements, as well as flex and grid items

    z-index controls stacking order and applies to positioned elements and to children of flex/grid containers. On a regular static block outside flex/grid it is ignored. Remember stacking contexts: z-index: 9999 won't help if the parent sits in a "lower" context.

  23. 23. How does rem differ from em?

    Correct answer: rem is relative to <html>'s font-size, em to the current element's font-size

    rem (root em) is always based on the font-size of <html> (usually 16px), so sizes are predictable. em depends on context and compounds when nested: font-size: 1.2em inside 1.2em gives 1.44 of the base. Window-relative units are vw/vh.

  24. 24. What is 50vw equal to?

    Correct answer: 50% of the viewport width

    vw is 1% of the viewport width, vh is 1% of its height. Percentages (%) depend on the parent. Caveat: 100vw includes the vertical scrollbar width and may cause horizontal scrolling, and on mobile 100vh ignores the collapsing browser toolbar - that's what dvh is for.

  25. 25. How are media queries usually written with a mobile-first approach?

    Correct answer: With min-width: base styles for mobile, additions for larger screens

    In mobile-first, the base CSS targets small screens, and @media (min-width: ...) adds styles as the screen grows. Mobile devices get the fewest overrides and styles are easier to build up. Using max-width is desktop-first. Tailwind breakpoints follow the same principle.

  26. 26. Why do you need <meta name="viewport" content="width=device-width, initial-scale=1">?

    Correct answer: So mobile browsers use the real screen width instead of emulating a ~980px desktop

    Without this tag, mobile browsers render the page as if on a wide screen and scale it down - mobile media queries don't fire and text is tiny. Disabling zoom (user-scalable=no) is bad for accessibility. The tag doesn't affect loading speed.

  27. 27. Along which axis does justify-content align items in a flex container?

    Correct answer: Along the main axis, which is set by flex-direction

    justify-content works on the main axis, align-items on the cross axis. With flex-direction: row the main axis is horizontal; with column it's vertical, and justify-content aligns vertically. So "always horizontally" is wrong.

  28. 28. A container has display: flex; flex-direction: column; justify-content: center. How are its children aligned?

    Correct answer: Centered vertically (if the container has free height)

    With flex-direction: column the main axis becomes vertical, so justify-content: center centers items vertically. Horizontal alignment is controlled by align-items in this case. The effect is visible only if the container is taller than its content.

  29. 29. What does flex-wrap: wrap do?

    Correct answer: Allows items to wrap onto a new line when they don't fit

    By default flex-wrap: nowrap - all items line up on one line and shrink (if flex-shrink allows) or overflow the container. With wrap, items move onto new lines. The alignment of those lines is set by align-content.

  30. 30. What's the simplest way to space flex items evenly without adding space after the last one?

    Correct answer: gap on the flex container

    gap adds space only between items - nothing extra at the edges. Both flex and grid support it. margin on items leaves an extra gap after the last one (you'd have to remove it with :last-child), and container padding is spacing from the edges, not between items.

  31. 31. Which approach correctly centers a block horizontally and vertically inside its parent?

    Correct answer: On the parent: display: flex; justify-content: center; align-items: center

    Flexbox with justify-content and align-items: center is the most common approach (Grid alternative: display: grid; place-items: center). text-align centers only inline content, and vertical-align doesn't work for blocks. margin: auto on a regular block centers only horizontally (and only with a set width); vertically it works inside flex/grid.

  32. 32. What does grid-template-columns: repeat(3, 1fr) define?

    Correct answer: Three columns that share the available space equally

    repeat(3, 1fr) is the same as 1fr 1fr 1fr. The fr unit is a fraction of the grid container's free space. Rows are defined with grid-template-rows. Caveat: 1fr means minmax(auto, 1fr) by default, so long content can stretch a column.

  33. 33. How do you make a grid item span the full width of the grid regardless of the number of columns?

    Correct answer: grid-column: 1 / -1

    Negative line numbers count from the end; -1 is the last line of the explicit grid, so 1 / -1 spans from the first line to the last. width: 100% only fills the item's own cell. CSS Grid has no span all syntax.

  34. 34. How does a pseudo-class differ from a pseudo-element?

    Correct answer: A pseudo-class is an element's state (:hover), a pseudo-element is a virtual part (::before)

    A pseudo-class selects an existing element in a particular state or position. A pseudo-element creates or targets a part of an element that isn't a separate DOM node. Per CSS3, pseudo-elements use two colons (::before) and pseudo-classes one; a single colon on legacy pseudo-elements is still supported for compatibility.

  35. 35. How do you make the last item of a list of any length red without JavaScript?

    Correct answer: li:last-child { color: red; }

    :last-child matches an element that is the last child of its parent. There are also :last-of-type (last element of its type) and :nth-last-child(). nth-child(10) only works with exactly 10 items, and there is no ::last pseudo-element.

  36. 36. Why doesn't a ::before with only width, height and background show up?

    Correct answer: The content property is missing

    ::before and ::after are generated only when content is set - even empty: content: "". They are also inline by default, so sizing needs display: block or inline-block (or positioning). They don't work on replaced elements like <img> and <input>.

  37. 37. How do you correctly declare and use a CSS variable?

    Correct answer: --main: red; color: var(--main);

    CSS custom properties are declared with two dashes and read with var(), optionally with a fallback: var(--main, black). $var is Sass syntax and @var is Less; those are resolved at build time. CSS variables live in the browser: they inherit, take part in the cascade and can change in media queries or via JS.

  38. 38. What do the last two digits in the color #3366ff80 mean?

    Correct answer: Transparency (alpha channel): 80 in hex ≈ 50%

    Hex notation supports 3, 4, 6 and 8 characters. #RRGGBBAA adds an alpha channel: 80 = 128 of 255 ≈ 50% opacity. The same color can be written as rgb(51 102 255 / 50%). Other formats include hsl(), oklch(), named colors and currentColor.

  39. 39. When is it better to use <img> rather than background-image?

    Correct answer: When the image is part of the content (product photo, illustration) and needs alt

    <img> is content: it has alt for accessibility, gets indexed by search engines, supports srcset and loading="lazy", and prints. background-image suits decoration: backgrounds, patterns and ornaments that carry no meaning. The file format doesn't affect the choice.

  40. 40. Why have heading levels <h1>–<h6> if size can be set with CSS?

    Correct answer: They define the document hierarchy for screen readers and search engines

    A heading level is semantics, not size. Screen reader users often navigate a page by headings. So don't skip levels for looks: set the size with CSS and choose the level based on structure.

  41. 41. When should you use <a> and when <button>?

    Correct answer: <a href> to navigate to a URL, <button> for an action on the page

    Links and buttons behave differently and have different semantics for screen readers: a link can be opened in a new tab and copied, and it activates with Enter; a button activates with Enter and Space. A <div onclick> instead of a button breaks keyboard accessibility. Buttons are fine outside forms with type="button".

  42. 42. What is the <dl> list for?

    Correct answer: For term–description pairs (<dt> and <dd>), such as a glossary

    <dl> (description list) contains <dt> (term) and <dd> (description) pairs. <ul> is an unordered list where order doesn't matter, <ol> is an ordered one. A dropdown in a form is <select> with <option>.

  43. 43. A form is submitted with the GET method. Where does the field data go?

    Correct answer: Into the URL query string (?name=value&...)

    With method="get" the data is encoded into the query string, so it's visible in the address bar and saved in history and logs - not suitable for passwords. POST sends data in the request body. Without JavaScript, a form is submitted via the action (URL) and method attributes of <form>.

  44. 44. What does <input type="email"> give you compared with type="text"?

    Correct answer: Built-in email format validation and a suitable keyboard on mobile

    The browser checks the address syntax (presence of @, etc.) on submit and shows a keyboard with @ on mobile. It doesn't check whether the mailbox exists, and encryption is provided by HTTPS. Built-in validation is complemented by required, pattern, minlength, but server-side validation is still mandatory.

  45. 45. What does the required attribute do on a form field?

    Correct answer: The browser won't submit the form while the field is empty

    required enables built-in client-side validation: with an empty field, submit is blocked and the field matches :invalid. Read-only is readonly. Client-side validation is just a convenience: it's easy to bypass, so the server must validate data itself.

  46. 46. What is the utility-first approach in Tailwind CSS about?

    Correct answer: Styles are composed in markup from small single-purpose classes (flex, p-4)

    Utility-first means styling with atomic classes, each doing one thing. Tailwind isn't a component library (unlike Bootstrap): it has no ready-made buttons. Only classes found in your source code end up in the final CSS, so the bundle stays small.

  47. 47. What does the md:flex class mean in Tailwind?

    Correct answer: display: flex applies on screens from the md breakpoint and wider

    Tailwind breakpoints are mobile-first: md: becomes @media (width >= 48rem), so the style applies from md upward. Without a prefix the style applies at all sizes. To apply a style only below a breakpoint, use max-md:.

  48. 48. What does p-4 equal in Tailwind with the default configuration?

    Correct answer: padding: 1rem

    Tailwind's spacing scale is based on a 0.25rem unit: p-4 = 4 × 0.25rem = 1rem. In v4 this is implemented with the --spacing variable: calc(var(--spacing) * 4). An arbitrary value looks like p-[4px].

  49. 49. How do you change a button's background on hover in Tailwind?

    Correct answer: bg-blue-500 hover:bg-blue-600

    States in Tailwind are set with variant prefixes: hover:, focus:, focus-visible:, active:, disabled: and so on. Prefixes can be combined: md:hover:bg-blue-600. Tailwind has no :hover- or on-hover: syntax.

  50. 50. How does the dark: variant work by default in Tailwind v4?

    Correct answer: Based on the system setting - via the prefers-color-scheme media query

    By default dark: relies on prefers-color-scheme. For a manual theme toggle, the variant is overridden with @custom-variant dark (&:where(.dark, .dark *)); - then the theme depends on a dark class on an ancestor. Tailwind doesn't consider the time of day.

  51. 51. When should you use <article> rather than <section>?

    Correct answer: For self-contained content like a post or a comment

    <article> could be syndicated or reused independently. <section> groups thematically related content within a page and usually has a heading. If neither fits, a plain <div> is fine.

  52. 52. How does <strong> differ from <b>?

    Correct answer: <strong> marks importance; <b> is only visual

    Both are bold by default, but semantics differ. Likewise <em> means stress emphasis, while <i> is for alternate voice (terms, foreign words). Choose by meaning, style with CSS.

  53. 53. What happens if you put a <div> inside a <p> in HTML?

    <p>Intro <div>Block</div> text</p>

    Correct answer: The parser closes the <p> before the <div>

    <p> may only contain phrasing content. The browser ends the paragraph early, leaving an empty <p></p> at the end - a frequent source of styling surprises and hydration mismatches.

  54. 54. When is <table> the right choice?

    Correct answer: For tabular data with rows and columns

    Tables give screen readers row/column relationships. Layout tables confuse assistive tech and are inflexible; use Grid or Flexbox for layout.

  55. 55. What is sent to the server for an unchecked checkbox?

    <input type="checkbox" name="subscribe" value="yes" />

    Correct answer: Nothing is sent for that field

    Only checked boxes are submitted (with their value, or on by default). The server should treat a missing field as "false".

  56. 56. Why isn't placeholder a replacement for <label>?

    Correct answer: It disappears once the user starts typing

    Use a visible <label> for the name and placeholder only for an example format. Users with memory or cognitive impairments especially struggle when the hint vanishes.

  57. 57. How should a group of related radio buttons be marked up?

    <fieldset>
      <legend>Delivery</legend>
      <label><input type="radio" name="delivery" value="courier" /> Courier</label>
      <label><input type="radio" name="delivery" value="pickup" /> Pickup</label>
    </fieldset>

    Correct answer: In a <fieldset> with one shared name

    The shared name makes them mutually exclusive. <legend> is announced as the group's label, so the user knows what "Courier" refers to.

  58. 58. What are <figure> and <figcaption> for?

    Correct answer: Self-contained media with a caption

    The caption is semantically linked to the content. alt still describes the image itself; <figcaption> is visible text for everyone.

  59. 59. How does overflow: auto differ from overflow: scroll?

    Correct answer: auto shows scrollbars only when needed

    overflow: hidden clips content without scrollbars. On many systems overlay scrollbars hide the difference, but on Windows scroll shows empty scrollbar tracks.

  60. 60. Why doesn't text-align: center center a <div> with a fixed width inside its parent?

    Correct answer: It aligns inline content, not the block itself

    text-align affects text and inline/inline-block children. A block with a width is centered with auto margins or by the parent's flex/grid alignment.

  61. 61. Why is a unitless line-height: 1.5 usually better than line-height: 24px?

    Correct answer: Children inherit the factor, not a fixed size

    With 24px (or 1.5em), children inherit the computed pixel value, so a large heading inside gets cramped lines. A unitless number scales with each element's font.

  62. 62. How does opacity: 0.5 on a card differ from background: rgb(0 0 0 / 0.5)?

    Correct answer: opacity affects the whole element and its children

    Use alpha in colors when only the background should be see-through. Note that opacity below 1 also creates a new stacking context.

  63. 63. How do you apply hover styles only on devices that can actually hover?

    @media (hover: hover) {
      .card:hover { transform: translateY(-2px); }
    }

    Correct answer: Wrap them in @media (hover: hover)

    On touch screens a tap can leave :hover "stuck" until the user taps elsewhere. Media features hover and pointer let you target capable devices.

  64. 64. What is the difference between .menu a and .menu > a?

    Correct answer: .menu > a matches only direct children

    The space is the descendant combinator, > is the child combinator. Using > limits the reach of styles in nested menus.

  65. 65. Which element does h2 + p select?

    Correct answer: A <p> right after an <h2> sibling

    + is the adjacent sibling combinator. h2 ~ p (general sibling) matches all following <p> siblings, not just the first.

  66. 66. What does input[type="email"] select?

    Correct answer: <input> elements whose type attribute equals email

    Attribute selectors also support ^= (starts with), $= (ends with) and *= (contains), e.g. a[href^="https"].

  67. 67. Why is img { max-width: 100%; height: auto; } a common base rule?

    Correct answer: Images shrink to fit, keeping their proportions

    Without it, a large image overflows a mobile layout. max-width (not width) prevents small images from being stretched.

  68. 68. What does margin: 10px 20px set?

    Correct answer: 10px top and bottom, 20px left and right

    The order is clockwise from the top: one value - all sides; two - vertical/horizontal; three - top/horizontal/bottom; four - top/right/bottom/left.

  69. 69. How do you make a square avatar image a circle?

    Correct answer: border-radius: 50%

    50% of the width and height turns a square into a circle and a rectangle into an ellipse. object-fit: cover crops non-square photos instead of squashing them.

  70. 70. Why end a font-family list with a generic family like sans-serif?

    font-family: "Inter", "Segoe UI", sans-serif;

    Correct answer: The browser then falls back to a similar style

    Fonts are tried left to right per character. Without a generic family you may get the browser default (often a serif) on systems missing your fonts.

  71. 71. What is the accessibility risk of reordering flex items with order?

    Correct answer: Visual order stops matching the DOM order

    Tab order and reading order follow the source. Use order (or row-reverse) only for cosmetic changes; for meaningful reordering change the markup.

  72. 72. Why do flex items in a row have equal height by default?

    Correct answer: The default align-items: stretch does that

    That is why cards in a row line up nicely. Set align-items: flex-start (or align-self on one item) to let items keep their content height.

  73. 73. Which style wins: a rule in a stylesheet or the inline style attribute?

    <p class="note" style="color: red">...</p>
    <!-- CSS: .note { color: blue; } -->

    Correct answer: Inline style, unless the rule has !important

    Inline styles beat any selector specificity. That's why they make overriding hard - prefer classes and keep inline styles for truly dynamic values.

  74. 74. What does class="hidden md:block" do in Tailwind?

    Correct answer: Hides it on small screens, shows it from md up

    Tailwind is mobile-first: unprefixed utilities apply everywhere, prefixed ones from that breakpoint up. md:hidden does the opposite.

  75. 75. Why set the lang attribute on <html>?

    <html lang="en">

    Correct answer: For correct pronunciation, hyphenation and quotes

    Parts in another language can be marked with their own lang (<span lang="fr">). hyphens: auto relies on lang to hyphenate correctly.