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.
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. 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. 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 thehiddenattribute). 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. How does
<div>differ from<span>by default?Correct answer:
<div>is a block element,<span>is an inline element<div>hasdisplay: blockby default: it stretches to the full width of its parent and starts on a new line.<span>hasdisplay: inline: it flows within text and is as wide as its content. Neither carries semantics - both are containers for grouping and styling.5. You set
width: 200px; height: 50pxon a<span>with no other styles. What happens?Correct answer: Width and height are ignored because
<span>is an inline elementwidthandheightdon't apply to inline elements - their size is determined by content. Verticalmargindoesn't push neighbors either. To size the element, it needsdisplay: inline-block,block, or must be a flex/grid item.6. How does
display: inline-blockdiffer frominline?Correct answer:
inline-blockstays in the line of text but accepts width, height and vertical spacinginline-blockis a hybrid: on the outside it behaves like an inline element (sits on the same line as its neighbors and respectsvertical-align), and on the inside like a block (width,height,paddingand verticalmarginwork). It'sblockthat starts on a new line, notinline-block.7. How do you read the value of the
data-user-id="42"attribute in JavaScript?Correct answer:
element.dataset.userIdAll
data-*attributes are available throughelement.dataset, with kebab-case names converted to camelCase:data-user-id→dataset.userId. The value is always a string. You can also usegetAttribute('data-user-id'). In CSS they are accessed via the[data-user-id]selector and theattr()function.8. What is the main difference between the
idandclassattributes?Correct answer:
idmust be unique on the page and has higher CSS specificity;classcan repeatAn
idvalue must be unique in the document: anchors (#section),label forand ARIA attributes reference it. Classes are reused across many elements, and one element can have several. Anidselector weighs (1,0,0) versus (0,1,0) for a class, which is why classes are usually preferred for styling.9. Why add
rel="noopener noreferrer"to a link withtarget="_blank"?Correct answer: So the opened tab doesn't get
window.openerand the source page's addressWithout
noopener, the new tab can usewindow.openerto replace the original page (reverse tabnabbing).noreferreradditionally omits the Referer header. Modern browsers already applynoopenerto_blankby default, but the attribute is still written explicitly. Indexing is affected bynofollow, not these values.10. What is the default
typeof a<button>inside a<form>?Correct answer:
submitBy 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 explicittype="button".11. Why link a
<label>to an<input>withforandid?Correct answer: Clicking the label focuses the field, and screen readers announce the label with it
A linked
labelenlarges 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 theinputinside thelabel.12. What
altshould 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. Ifaltis missing, a screen reader may read out the file name. Text like "image" is useless:altshould convey the image's meaning, not the fact that it exists.13. What does
box-sizing: border-boxdo?Correct answer: Includes
paddingandborderin the specifiedwidthandheightWith
content-box(the default),widthsets only the content width, andpaddingandborderare added on top:width: 200px+padding: 20px= 240px. Withborder-box, the total width is exactly 200px and the content shrinks. That's why many CSS resets applyborder-boxto every element.marginis never part of the size.14. How does
paddingdiffer frommargin?Correct answer:
paddingis inner spacing (painted with background),marginis outer spacing (always transparent)The box model order is content → padding → border → margin.
paddingsits inside the border and is painted with the element's background;marginis outside and transparent. Also, vertical margins of adjacent blocks can collapse while padding never does, andmargincan be negative whilepaddingcannot.15. Two blocks are stacked. The top one has
margin-bottom: 20px, the bottom onemargin-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. Both selectors set
coloron the same link. Which wins:#nav aor.menu .item a.link?Correct answer:
#nav a- a single ID outweighs any number of classesSpecificity 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. Which of these properties is inherited by child elements by default?
Correct answer:
colorMostly 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 theinheritvalue.18. How does
display: nonediffer fromvisibility: hidden?Correct answer:
display: noneremoves the element from layout;visibility: hiddenhides it but keeps its spaceWith
display: nonethe element isn't rendered and takes no space - neighbors shift. Withvisibility: hiddenit's invisible but its space remains.opacity: 0also 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. How does an element with
position: relative; top: 10pxbehave?Correct answer: It shifts 10px down from its normal spot, but that spot in the flow is preserved
relativevisually shifts the element relative to where it would be in normal flow, but its space isn't released - neighbors don't move.relativeis also often set on a parent to make it the reference point for absolutely positioned children. Positioning relative to the window isfixed.20. What is an element with
position: absolutepositioned relative to?Correct answer: The nearest ancestor whose
positionis notstaticAn 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 getsposition: relative.21. How does
position: sticky; top: 0work?Correct answer: The element stays in flow until scrolling reaches
top: 0, then "sticks" - within its parentstickyis a hybrid ofrelativeandfixed: before the threshold it's in flow, after it - pinned until its parent container ends. Common reasons sticky "doesn't work": notopis set, an ancestor hasoverflow: hidden/auto, or the parent is no taller than the element itself.22. Which elements does
z-indexapply to?Correct answer: Positioned elements, as well as flex and grid items
z-indexcontrols stacking order and applies to positioned elements and to children of flex/grid containers. On a regularstaticblock outside flex/grid it is ignored. Remember stacking contexts:z-index: 9999won't help if the parent sits in a "lower" context.23. How does
remdiffer fromem?Correct answer:
remis relative to<html>'sfont-size,emto the current element'sfont-sizerem(root em) is always based on thefont-sizeof<html>(usually 16px), so sizes are predictable.emdepends on context and compounds when nested:font-size: 1.2eminside1.2emgives 1.44 of the base. Window-relative units arevw/vh.24. What is
50vwequal to?Correct answer: 50% of the viewport width
vwis 1% of the viewport width,vhis 1% of its height. Percentages (%) depend on the parent. Caveat:100vwincludes the vertical scrollbar width and may cause horizontal scrolling, and on mobile100vhignores the collapsing browser toolbar - that's whatdvhis for.25. How are media queries usually written with a mobile-first approach?
Correct answer: With
min-width: base styles for mobile, additions for larger screensIn 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. Usingmax-widthis desktop-first. Tailwind breakpoints follow the same principle.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. Along which axis does
justify-contentalign items in a flex container?Correct answer: Along the main axis, which is set by
flex-directionjustify-contentworks on the main axis,align-itemson the cross axis. Withflex-direction: rowthe main axis is horizontal; withcolumnit's vertical, andjustify-contentaligns vertically. So "always horizontally" is wrong.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: columnthe main axis becomes vertical, sojustify-content: centercenters items vertically. Horizontal alignment is controlled byalign-itemsin this case. The effect is visible only if the container is taller than its content.29. What does
flex-wrap: wrapdo?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 (ifflex-shrinkallows) or overflow the container. Withwrap, items move onto new lines. The alignment of those lines is set byalign-content.30. What's the simplest way to space flex items evenly without adding space after the last one?
Correct answer:
gapon the flex containergapadds space only between items - nothing extra at the edges. Both flex and grid support it.marginon items leaves an extra gap after the last one (you'd have to remove it with:last-child), and containerpaddingis spacing from the edges, not between items.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: centerFlexbox with
justify-contentandalign-items: centeris the most common approach (Grid alternative:display: grid; place-items: center).text-aligncenters only inline content, andvertical-aligndoesn't work for blocks.margin: autoon a regular block centers only horizontally (and only with a set width); vertically it works inside flex/grid.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 as1fr 1fr 1fr. Thefrunit is a fraction of the grid container's free space. Rows are defined withgrid-template-rows. Caveat:1frmeansminmax(auto, 1fr)by default, so long content can stretch a column.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 / -1Negative line numbers count from the end;
-1is the last line of the explicit grid, so1 / -1spans from the first line to the last.width: 100%only fills the item's own cell. CSS Grid has nospan allsyntax.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. How do you make the last item of a list of any length red without JavaScript?
Correct answer:
li:last-child { color: red; }:last-childmatches 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::lastpseudo-element.36. Why doesn't a
::beforewith onlywidth,heightandbackgroundshow up?Correct answer: The
contentproperty is missing::beforeand::afterare generated only whencontentis set - even empty:content: "". They are also inline by default, so sizing needsdisplay: blockorinline-block(or positioning). They don't work on replaced elements like<img>and<input>.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).$varis Sass syntax and@varis 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. What do the last two digits in the color
#3366ff80mean?Correct answer: Transparency (alpha channel):
80in hex ≈ 50%Hex notation supports 3, 4, 6 and 8 characters.
#RRGGBBAAadds an alpha channel:80= 128 of 255 ≈ 50% opacity. The same color can be written asrgb(51 102 255 / 50%). Other formats includehsl(),oklch(), named colors andcurrentColor.39. When is it better to use
<img>rather thanbackground-image?Correct answer: When the image is part of the content (product photo, illustration) and needs
alt<img>is content: it hasaltfor accessibility, gets indexed by search engines, supportssrcsetandloading="lazy", and prints.background-imagesuits decoration: backgrounds, patterns and ornaments that carry no meaning. The file format doesn't affect the choice.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. When should you use
<a>and when<button>?Correct answer:
<a href>to navigate to a URL,<button>for an action on the pageLinks 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 withtype="button".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. A form is submitted with the
GETmethod. 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.POSTsends data in the request body. Without JavaScript, a form is submitted via theaction(URL) andmethodattributes of<form>.44. What does
<input type="email">give you compared withtype="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 byrequired,pattern,minlength, but server-side validation is still mandatory.45. What does the
requiredattribute do on a form field?Correct answer: The browser won't submit the form while the field is empty
requiredenables built-in client-side validation: with an empty field,submitis blocked and the field matches:invalid. Read-only isreadonly. Client-side validation is just a convenience: it's easy to bypass, so the server must validate data itself.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. What does the
md:flexclass mean in Tailwind?Correct answer:
display: flexapplies on screens from themdbreakpoint and widerTailwind breakpoints are mobile-first:
md:becomes@media (width >= 48rem), so the style applies frommdupward. Without a prefix the style applies at all sizes. To apply a style only below a breakpoint, usemax-md:.48. What does
p-4equal in Tailwind with the default configuration?Correct answer:
padding: 1remTailwind's spacing scale is based on a 0.25rem unit:
p-4= 4 × 0.25rem = 1rem. In v4 this is implemented with the--spacingvariable:calc(var(--spacing) * 4). An arbitrary value looks likep-[4px].49. How do you change a button's background on hover in Tailwind?
Correct answer:
bg-blue-500 hover:bg-blue-600States 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-oron-hover:syntax.50. How does the
dark:variant work by default in Tailwind v4?Correct answer: Based on the system setting - via the
prefers-color-schememedia queryBy default
dark:relies onprefers-color-scheme. For a manual theme toggle, the variant is overridden with@custom-variant dark (&:where(.dark, .dark *));- then the theme depends on adarkclass on an ancestor. Tailwind doesn't consider the time of day.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. How does
<strong>differ from<b>?Correct answer:
<strong>marks importance;<b>is only visualBoth 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. 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. 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. 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, oronby default). The server should treat a missing field as "false".56. Why isn't
placeholdera replacement for<label>?Correct answer: It disappears once the user starts typing
Use a visible
<label>for the name andplaceholderonly for an example format. Users with memory or cognitive impairments especially struggle when the hint vanishes.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 sharednameThe shared
namemakes them mutually exclusive.<legend>is announced as the group's label, so the user knows what "Courier" refers to.58. What are
<figure>and<figcaption>for?Correct answer: Self-contained media with a caption
The caption is semantically linked to the content.
altstill describes the image itself;<figcaption>is visible text for everyone.59. How does
overflow: autodiffer fromoverflow: scroll?Correct answer:
autoshows scrollbars only when neededoverflow: hiddenclips content without scrollbars. On many systems overlay scrollbars hide the difference, but on Windowsscrollshows empty scrollbar tracks.60. Why doesn't
text-align: centercenter a<div>with a fixed width inside its parent?Correct answer: It aligns inline content, not the block itself
text-alignaffects 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. Why is a unitless
line-height: 1.5usually better thanline-height: 24px?Correct answer: Children inherit the factor, not a fixed size
With
24px(or1.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. How does
opacity: 0.5on a card differ frombackground: rgb(0 0 0 / 0.5)?Correct answer:
opacityaffects the whole element and its childrenUse alpha in colors when only the background should be see-through. Note that
opacitybelow 1 also creates a new stacking context.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 featureshoverandpointerlet you target capable devices.64. What is the difference between
.menu aand.menu > a?Correct answer:
.menu > amatches only direct childrenThe space is the descendant combinator,
>is the child combinator. Using>limits the reach of styles in nested menus.65. Which element does
h2 + pselect?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. What does
input[type="email"]select?Correct answer:
<input>elements whosetypeattribute equalsemailAttribute selectors also support
^=(starts with),$=(ends with) and*=(contains), e.g.a[href^="https"].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(notwidth) prevents small images from being stretched.68. What does
margin: 10px 20pxset?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. 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: covercrops non-square photos instead of squashing them.70. Why end a
font-familylist with a generic family likesans-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. 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(orrow-reverse) only for cosmetic changes; for meaningful reordering change the markup.72. Why do flex items in a row have equal height by default?
Correct answer: The default
align-items: stretchdoes thatThat is why cards in a row line up nicely. Set
align-items: flex-start(oralign-selfon one item) to let items keep their content height.73. Which style wins: a rule in a stylesheet or the inline
styleattribute?<p class="note" style="color: red">...</p> <!-- CSS: .note { color: blue; } -->Correct answer: Inline
style, unless the rule has!importantInline styles beat any selector specificity. That's why they make overriding hard - prefer classes and keep inline styles for truly dynamic values.
74. What does
class="hidden md:block"do in Tailwind?Correct answer: Hides it on small screens, shows it from
mdupTailwind is mobile-first: unprefixed utilities apply everywhere, prefixed ones from that breakpoint up.
md:hiddendoes the opposite.75. Why set the
langattribute 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: autorelies onlangto hyphenate correctly.