HTML & CSS MCQs multiple-choice questions with answers & explanations
All 28 HTML & CSS quiz questions on one page. Pick an answer in your head, then open Show answer to check it and read why. Want a score and a timer? Take them as a quiz instead.
- 1.easy
How wide is
.cardon screen, measured from the outer edges of its border?.card { box-sizing: content-box; width: 200px; padding: 20px; border: 5px solid; margin: 10px; }- A
200px - B
240px - C
250px - D
270px
Show answer
Answer: C (
250px)With
content-box,widthsets only the content area, so padding (2 × 20px) and border (2 × 5px) are added on top: 200 + 40 + 10 = 250px. Margin lies outside the border, so 270px is wrong. Withbox-sizing: border-boxthe box would be exactly 200px. - A
- 2.easy
What are the computed font sizes of
.childand.label?html { font-size: 16px; } .parent { font-size: 20px; } .child { font-size: 1.5em; } /* inside .parent */ .label { font-size: 1.5rem; } /* inside .child */- A
24pxand24px - B
30pxand45px - C
24pxand36px - D
30pxand24px
Show answer
Answer: D (
30pxand24px)For
font-size,emis relative to the parent's font size, so.childis 1.5 × 20 = 30px, and nestedemvalues compound.remis always relative to the root (html) font size, so.labelis 1.5 × 16 = 24px however deeply it is nested. - A
- 3.mid
How much vertical space separates the two paragraphs?
.first { margin-bottom: 20px; } .second { margin-top: 30px; } /* .first and .second are adjacent <p> siblings in a normal block container */- A
50px - B
30px - C
20px - D
25px
Show answer
Answer: B (
30px)Adjacent vertical margins of block-level boxes in normal flow collapse into one margin the size of the larger, so the gap is 30px, not 50px. Margins never collapse horizontally, and they do not collapse between flex or grid items.
- A
- 4.mid
The link is being hovered. What color is it?
/* <nav id="sidebar" class="nav"><ul class="menu"><li><a href="#">Home</a></li></ul></nav> */ #sidebar a { color: red; } .nav .menu li a:hover { color: blue; }- A
blue, because the second rule has more selectors - B
blue, because it comes later in the stylesheet - C
red, because one ID outranks any number of classes and pseudo-classes - DIt depends on the browser
Show answer
Answer: C (
red, because one ID outranks any number of classes and pseudo-classes)Specificity is compared column by column:
#sidebar ais (1,0,1) and.nav .menu li a:hoveris (0,3,2). The ID column decides first, so red wins even though the blue rule has more parts and comes later. Source order only breaks exact ties. - A
- 5.mid
What color is the paragraph text?
<style> p { color: red !important; } </style> <p style="color: blue">Hello</p>- A
blue, because inline styles always win - BWhichever declaration the browser parses last
- C
blue, because inline styles have the highest specificity - D
red, because an!importantdeclaration beats a normal inline one
Show answer
Answer: D (
red, because an!importantdeclaration beats a normal inline one)The cascade checks importance before it looks at the style attribute or specificity, so an author
!importantrule beats every normal author declaration, inline styles included. Only an inline declaration that is itself!importantwould win back, which is why!importantin shared CSS is so hard to override. - A
- 6.mid
What does
flex: 1expand to?- A
flex: 1 1 auto - B
flex: 1 0 0% - C
flex: 1 1 0% - D
flex: 0 1 auto
Show answer
Answer: C (
flex: 1 1 0%)A single unitless number sets
flex-grow, keepsflex-shrink: 1and setsflex-basisto zero (browsers report0%). Because the basis is zero, items withflex: 1split the space equally regardless of their content.flex: autois1 1 auto, and the initial value is0 1 auto. - A
- 7.mid
Assuming short content in each cell, how wide are the three columns?
.grid { display: grid; width: 800px; grid-template-columns: 200px 1fr 2fr; column-gap: 30px; }- A
200px 200px 400px - B
200px 180px 360px - C
200px 300px 300px - D
266px 266px 266px
Show answer
Answer: B (
200px 180px 360px)frunits share the space left after fixed tracks and gaps: 800 − 200 − 2 × 30 = 540px, split into 3 fractions of 180px, so the columns are 200px, 180px and 360px. Forgetting the gaps gives 200/200/400. With long unbreakable content, a1frtrack (reallyminmax(auto, 1fr)) can grow beyond its share. - A
- 8.easy
An element has
position: absolute; top: 0; left: 0. What is it positioned relative to?- AIts parent element, always
- BThe nearest ancestor whose
positionis notstatic, or the initial containing block if there is none - CThe viewport, always
- DThe nearest ancestor with
display: block
Show answer
Answer: B (The nearest ancestor whose
positionis notstatic, or the initial containing block if there is none)An absolutely positioned element is placed against the padding box of its containing block: the nearest positioned ancestor (
relative,absolute,fixedorsticky). Ancestors with atransformorfilteralso qualify. With none, it falls back to the initial containing block. That is why you putposition: relativeon the parent you want to anchor to. - 11.easy
Why is a
<button>preferred over a<div>with a click handler for a clickable control?- AA
<div>cannot receive click events - BClick events on a
<div>do not bubble - C
<button>is focusable, activates with Enter and Space, and is announced as a button, with no extra code - D
<button>elements render faster than<div>elements
Show answer
Answer: C (
<button>is focusable, activates with Enter and Space, and is announced as a button, with no extra code)A
<div>gets clicks just fine, but it is not in the tab order, ignores the keyboard and has no role, so keyboard and screen-reader users cannot operate it. Rebuilding a button takesrole="button",tabindex="0"and Enter/Space key handlers; the native element gives you all of that for free. - AA
- 12.easy
Clicking the label does not focus the input, and screen readers announce the field without a label. Why?
<label for="email">Email</label> <input type="email" name="email" />- A
formatches an element'sid, and this input only has aname - BA
<label>must wrap its input to be associated with it - C
type="email"inputs cannot be labelled - DThe input also needs an
aria-label
Show answer
Answer: A (
formatches an element'sid, and this input only has aname)A
<label for="x">is associated with the element whoseidisx;nameis only used when the form is submitted. Addid="email"to the input, or wrap the input inside the label for implicit association. Addingaria-labelon top of a working label is redundant. - A
- 13.easy
What is the right
altvalue for a purely decorative image?- ALeave out the
altattribute - B
alt="image" - C
alt="" - D
alt="decorative"
Show answer
Answer: C (
alt="")An empty
alt=""tells assistive technology to skip the image. Leavingaltout is worse, because many screen readers then read out the file name. Words like "image" or "decorative" are just noise, since the screen reader already announces it as an image. - ALeave out the
- 15.easy
Which of these properties is inherited by child elements by default?
- A
margin - B
color - C
border - D
background-color - E
padding
Show answer
Answer: B (
color)Text-related properties inherit:
color, thefont-*properties,line-height,text-align,visibilityandcursor. Box properties such asmargin,padding,borderandbackground-colordo not. A child often seems to share its parent's background only because its ownbackground-coloristransparent. - A
- 16.easy
Which declaration is required for a
::beforepseudo-element to be generated at all?- A
content - B
display: block - C
position: absolute - D
z-index
Show answer
Answer: A (
content)Without
content, its computed value isnoneand no::beforeor::afterbox is created, whatever else you set. For purely decorative shapes usecontent: ''. The generated box isinlineby default, so it also needsdisplay: inline-blockorblockbeforewidthandheightapply. - A
- 17.mid
Which paragraph turns red?
<style> .post p:nth-child(2) { color: red; } </style> <div class="post"> <h2>Title</h2> <p>First</p> <p>Second</p> </div>- AThe "Second" paragraph
- BNeither paragraph
- CThe "First" paragraph
- DBoth paragraphs
Show answer
Answer: C (The "First" paragraph)
:nth-child(2)counts all siblings regardless of type, then checks the rest of the selector. The second child of.postis the "First" paragraph, and it is ap, so it matches. To select the secondp, usep:nth-of-type(2), or:nth-child(2 of p)in modern browsers. - 18.hard
What color is the paragraph?
/* <div class="content"><p>Text</p></div> */ :is(#main, .content) p { color: red; } :where(#main, .content) p { color: blue; } .content p { color: green; }- A
red, because:is()takes the specificity of its most specific argument - B
blue, because:where()rules override:is()rules - C
green, because.content pcomes last and matches through a class - D
green, because all three rules tie and the last one wins
Show answer
Answer: A (
red, because:is()takes the specificity of its most specific argument)The specificity of
:is()is that of its most specific argument,#main, even though this element matched through.content, so the first rule is (1,0,1).:where()always contributes zero, so the second rule is (0,0,1), and.content pis (0,1,1). Red wins.:not()and:has()count specificity the same way as:is(). - A
- 19.hard
A flex item with
flex: 1contains a long unbreakable string and overflows its container instead of shrinking. What is the usual fix?- ASet
flex-shrink: 1on the item - BSet
flex-basis: 0on the item - CSet
width: 100%on the container - DSet
min-width: 0(oroverflow: hidden) on the item
Show answer
Answer: D (Set
min-width: 0(oroverflow: hidden) on the item)Flex items default to
min-width: auto, which stops them shrinking below their min-content width, here the width of the long string.flex: 1already includesflex-shrink: 1and a zero basis, so neither of those helps.min-width: 0removes the floor, and so does making the item a scroll container withoverflow: hidden. Then you can clip or truncate the text inside it. - ASet
- 20.hard
How much top padding does
.childget?.parent { width: 400px; height: 100px; } .child { padding-top: 50%; } /* .child is inside .parent */- A
50px - B
200px - C
0, because the child has no height - DIt depends on the content
Show answer
Answer: B (
200px)Percentage padding and margin, vertical ones included, resolve against the containing block's width (its inline size), not its height. So 50% of 400px is 200px. The old padding trick for fixed aspect-ratio boxes relied on this; today you would use
aspect-ratio. - A
- 21.mid
At a viewport width of 800px, what is the font size of
.title?.title { font-size: 16px; } @media (min-width: 600px) { .title { font-size: 24px; } } @media (min-width: 400px) { .title { font-size: 20px; } }- A
16px - B
24px - C
20px
Show answer
Answer: C (
20px)Both media queries match at 800px, and a media query adds no specificity, so the two rules tie and the later one wins: 20px. With mobile-first
min-widthqueries, order them from the smallest breakpoint to the largest so the widest match comes last. - A
- 22.hard
Where
.modaland theheaderoverlap, which one is painted on top?<div class="wrapper" style="position: relative; z-index: 1"> <div class="modal" style="position: fixed; z-index: 9999"></div> </div> <header style="position: relative; z-index: 2"></header>- A
.modal, because 9999 is the highestz-index - BThe
header, because.modalis confined to the stacking context of.wrapper - C
.modal, becauseposition: fixedescapes its ancestors - DWhichever comes later in the DOM
Show answer
Answer: B (The
header, because.modalis confined to the stacking context of.wrapper).wrapperis positioned withz-index: 1, so it forms a stacking context..modalis stacked inside it, and the wrapper as a whole is compared with the header: 1 against 2.position: fixedchanges how the modal is positioned, not which stacking context it belongs to. Render the modal outside the wrapper (a portal), or use the top layer withdialog.showModal(). - A
- 23.hard
Which declaration does NOT create a new stacking context on its own?
- A
opacity: 0.9 - B
transform: translateZ(0) - C
position: relative(withz-index: auto) - D
isolation: isolate - E
position: fixed
Show answer
Answer: C (
position: relative(withz-index: auto))A relatively positioned element forms a stacking context only once it has a
z-indexother thanauto.opacitybelow 1, anytransform,isolation: isolateandposition: fixedorstickycreate one immediately, which is why adding an innocent-lookingtransformcan suddenly trap a child that has a highz-index. - A
- 24.mid
Two scripts need the parsed DOM, and
b.jsdepends ona.js. Which option loads them without blocking the HTML parser and runs them in order?- A
asyncon bothscripttags - BPlain
scripttags at the top of thehead - C
asyncona.jsanddeferonb.js - D
deferon bothscripttags
Show answer
Answer: D (
deferon bothscripttags)deferscripts download in parallel with parsing and run in document order once parsing finishes, just beforeDOMContentLoaded.asyncscripts run as soon as each one arrives, in any order and possibly mid-parse, so they suit independent scripts like analytics. Plain scripts in the head block the parser. Module scripts (type="module") are deferred by default. - A
- 25.mid
A web font is referenced only inside a CSS file, so the browser discovers it late. Which tag fetches it early for the current page?
- A
<link rel="prefetch" href="/font.woff2"> - B
<link rel="dns-prefetch" href="https://fonts.example"> - C
<link rel="preconnect" href="https://fonts.example"> - D
<link rel="preload" href="/font.woff2" as="font" type="font/woff2" crossorigin>
Show answer
Answer: D (
<link rel="preload" href="/font.woff2" as="font" type="font/woff2" crossorigin>)preloadrequests a high-priority fetch of a resource the current page will need.as="font"sets the right priority and request type, andcrossoriginis required because fonts are always fetched in CORS mode, even from your own origin.prefetchis a low-priority hint for future navigations, anddns-prefetchandpreconnectonly warm up the connection. - A
- 26.mid
Images push content down as they load, causing layout shift. What is the simplest fix?
- ASet
widthandheightattributes on eachimgso the browser can reserve space from the aspect ratio - BAdd
loading="lazy"to every image - CConvert the images to WebP
- DGive the images
display: block
Show answer
Answer: A (Set
widthandheightattributes on eachimgso the browser can reserve space from the aspect ratio)Browsers use the
widthandheightattributes to compute anaspect-ratiobefore the file arrives, so with CSS likewidth: 100%; height: autothe box already has the right size and nothing shifts. Lazy loading and smaller formats help loading speed but not Cumulative Layout Shift. For other containers, CSSaspect-ratiodoes the same job. - ASet
- 27.hard
Which change is most likely to make Largest Contentful Paint (LCP) worse?
- AAdding
loading="lazy"to the above-the-fold hero image - BAdding
fetchpriority="high"to the hero image - CServing the hero image as AVIF
- DPreloading the hero image
Show answer
Answer: A (Adding
loading="lazy"to the above-the-fold hero image)Lazy images are not requested until layout shows they are near the viewport, so a lazy hero image starts downloading late and LCP suffers. Load above-the-fold images eagerly, ideally with
fetchpriority="high"or a preload, and keeploading="lazy"for images further down the page. A smaller format such as AVIF usually helps. - AAdding
- 28.hard
Which property is usually cheapest to animate for smooth 60 fps motion?
- A
left - B
width - C
transform - D
margin-left
Show answer
Answer: C (
transform)Changing
left,widthormargin-leftchanges geometry, so every frame re-runs layout and paint.transform(likeopacity) can be applied by the compositor to an already-painted layer, often off the main thread, so it stays smooth even when JavaScript is busy. Animatetransform: translateX()instead ofleft. - A