Semantic HTML
Semantic HTML involves using appropriate tags to convey meaning and structure. It enhances accessibility, improves SEO by helping search engines understand content hierarchy, ensures readability without CSS, and simplifies code maintenance.
DOCTYPE and Rendering Modes
The <!DOCTYPE> declaration must appear at the top of an HTML document to instruct the browser to use standards mode. Without it—or with an invalid declaration—the browser falls back to quirks (compatibility) mode, which emulates legacy rendering behaviors for backward compatibility.
CSS Box Model
Every HTML element is treated as a rectangular box composed of content, padding, border, and margin. Two models exist:
- W3C Standard Box Model:
widthandheightapply only to the content area. - IE (Quirks) Box Model:
widthandheightinclude content, padding, and border.
The box-sizing property controls this behavior:
content-box(default): standard model.border-box: includes padding and border in width/height.
Block Formatting Context (BFC)
A BFC is an independent layout container where internal elements don’t interfere with external ones. Key properties:
- Floats don’t intrude into the BFC area.
- Margins of child elements don’t collapse with those outside.
- Height accounts for floated children.
Triggers for BFC creation:
floatnotnoneposition: absoluteorfixeddisplay: inline-block,table-cell,flex, etc.overflowother thanvisible
CSS Selectors and Inheritance
Common selectors include ID (#id), class (.class), tag (div), descendant (ul li), child (ul > li), adjacent sibling (h1 + p), attribute ([type="text"]), and pseudo-classes (:hover).
Inheritable properties: font-family, color, font-size, line-height.
Non-inheritable: margin, padding, border, width, height.
Specificity and Cascade
Specificity determines which styles apply when rules conflict:
!importantoverrides all.- Inline styles > ID > class/attribute/pseudo-class > tag.
- Later rules override earlier ones if specificity is equal.
Pseudo-classes vs. Pseudo-elements
- Pseudo-classes (
:hover,:nth-child) target element states. - Pseudo-elements (
::before,::after) create virtual elements.
Pseudo-elements can only appear once per selector and must be last. They have tag-level specificity; pseudo-classes have class-level specificity.
Display Values and Box Sizing
Key display values:
block: full-width, line break before/after.inline: flows with text, ignores width/height.inline-block: inline flow but respects dimensions.none: removes from layout entirely.flex,grid: enable modern layout models.
box-sizing options:
content-box: default W3C behavior.border-box: includes padding/border in size calculations.
Margin Collapse
Vertical margins between adjacent or nested block elements may merge into a single margin:
- Both positive → larger value.
- Both negative → larger absolute value.
- Mixed signs → algebraic sum.
Hiding Elements
display: none: removes from layout.visibility: hidden: hides but preserves space.opacity: 0: fully transparent, still interactive.- Offscreen positioning (
left: -9999px). transform: scale(0): visually hidden but occupies original space.
Line Height
line-height defines the vertical space between baselines of text lines. It controls vertical spacing even when no explicit height is set. Setting line-height equal to height centers single-line text vertically.
Element Categories
- Inline:
span,a,img,input— no line breaks, ignore width/height. - Block:
div,p,h1–h6,ul— full width, stack vertically. - Void (self-closing):
br,hr,img,input,meta,link.
Positioning Schemes
static: default flow.relative: offset from normal position.absolute: positioned relative to nearest non-staticancestor.fixed: fixed relative to viewport.
HTML5 Features
New semantic tags: header, nav, section, article, footer.
Media elements: <video>, <audio>.
Graphics: <canvas>, SVG.
Form enhancements: new input types (email, date, etc.).
Storage: localStorage (persistent), sessionStorage (session-only).
APIs: Geolocation, Web Workers, WebSockets.
Distinction from HTML4: simplified <!DOCTYPE html>, new elements, native APIs.
SVG vs. Canvas
- SVG: vector-based, XML-defined, DOM-accessible, resolution-independent. Changes auto-re-render.
- Canvas: raster-based, script-drawn pixel grid. No object retention—entire scene must be redrawn for updates.
CSS Reset
Browsers apply inconsistent default styles. Resetting (* { margin: 0; padding: 0 }) or normalizing (Normalize.css) ensures consistent baseline styling.
Opacity vs. RGBA
opacity: affects entire element and all children.rgba(): applies transparency only to the targeted property (e.g., background), without affecting descendants.
Client-Side Storage
| Feature | Cookie | localStorage | sessionStorage |
|---|---|---|---|
| Size | ~4KB | ~5–10MB | ~5–10MB |
| Persistence | Until expiry | Persistent | Session-only |
| Sent to server? | Yes | No | No |
HTML5 Application Cache (Deprecated)
Historically, the manifest attribute triggered offline caching. The browser would:
- Fetch the manifest on first visit and cache listed resources.
- On subsequent visits, compare manifests and update if changed.
- Use cached assets when offline.
Note: AppCache is now deprecated in favor of Service Workers.
<link> vs. @import
<link>: HTML tag, loads CSS in parallel, supports alternate stylesheets/RSS.@import: CSS directive, loads sequentially after page render starts, limited IE support (< IE5).
Clearing Floats
- clearfix:
.container::after { content: ''; display: table; clear: both; } - Add non-floated clearing element (
<div style="clear:both"></div>). - Set
overflow: hidden(requires explicit width in older IE). - Float the parent.
Responsive Design
Responsive design uses fluid grids, flexible images, and media queries (@media) to adapt layouts across devices. For legacy IE (<9), polyfills like respond.js or JavaScript-based viewport detection can provide fallback support.
Centering Techniques
Horizontal:
text-align: center(inline/inline-block children).margin: 0 auto(block with defined width).- Flexbox:
justify-content: center. - Grid:
justify-items: center.
Vertical:
- Flexbox:
align-items: center. - Absolute positioning +
transform: translateY(-50%). - Table-cell with
vertical-align: middle. - Known height:
top: 50%+ negativemargin-top.
Flexbox Layout
Flexbox creates responsive, direction-agnostic layouts. A flex container (display: flex) distributes space among children (flex items). Key traits:
- Items ignore
float,clear, andvertical-align. - Grows/shrinks based on available space.
- Simplifies alignment and distribution.
CSS Units
px: absolute pixel unit.em: relative to parent’sfont-size.rem: relative to root (<html>)font-size.%: relative to parent dimension.vw/vh: 1% of viewport width/height.vmin/vmax: based on smaller/larger viewport dimension.
Fixed-Left, Fluid-Right Layout
- Float: left column floated with fixed width; right uses
margin-left. - Absolute positioning: left absolutely positioned; right uses
margin-left. - BFC: left floated; right uses
overflow: hiddento form BFC. - Flexbox: container
display: flex; leftwidth: fixed; rightflex: 1.
CSS Animation Example
.bounce {
width: 20px;
height: 20px;
background: red;
position: relative;
animation: slide 3s infinite;
}
@keyframes slide {
from { left: 0; }
to { left: 200px; }
}
CSS Triangle
.arrow {
width: 0;
height: 0;
border: 20px solid transparent;
border-top-color: red;
}
Mobile Layout Strategies
- Fluid grids (%-based widths).
- Flexbox for flexible alignment.
rem+ media queries for scalable typography.- Viewport meta tag for proper scaling.
Holy Grail and Double-Wing Layouts
Both achieve three-column layouts with a fluid center and fixed sidebars, prioritizing main content in source order.
- Holy Grail: Uses floats, negative margins, and relative positioning.
- Double-Wing: Avoids relative positioning by applying side margins to the center column and using negative margins on sidebars.
Flex Alignment: align-items vs align-content
align-items: aligns items along cross axis (works for single/multi-line).align-content: distributes lines in multi-line flex containers (no effect on single line).
Removing inline-block Gaps
Whitespace between inline-block elements renders as a space. Fixes:
- Set parent
font-size: 0. - Use negative
margin. - Adjust
letter-spacingorword-spacing. - Remove whitespace in HTML.
Semantic Tag Differences
<title>(attribute) vs<h1>:h1denotes document structure;titleis metadata.<b>vs<strong>:bis stylistic;strongimplies importance.<i>vs<em>:iis typographic;emindicates emphasis.
Script Loading Attributes
- Default: blocks HTML parsing until script downloads and executes.
async: downloads in parallel; executes immediately upon download (order not guaranteed).defer: downloads in parallel; executes after document parsing, in order.
Custom Data Attributes
data-* attributes embed custom data in HTML:
<div data-user-id="123"></div>
Accessible via JavaScript (element.dataset.userId) or CSS ([data-role="admin"]). Must be lowercase and contain at least one character after data-.
Cross-Tab Communication
Techniques:
localStorageevents (storageevent listener).BroadcastChannelAPI.- Shared workers (
SharedWorker).
1px Line Without Border
<div style="height: 1px; background: red; overflow: hidden;"></div>
Reliable across rendering modes.
Sub-12px Text in Chrome
.small-text {
font-size: 10px;
-webkit-transform: scale(0.833);
transform-origin: left top;
display: inline-block;
}
Full-Screen 'Pin' Layout
- Top section:
width: 100%. - Bottom row: two
width: 50%columns usingfloat: leftordisplay: inline-block.
Common Browser Compatibility Issues
- IE6 PNG24 transparency: use PNG8.
- Default margins/padding: reset globally.
- Chrome text scaling:
-webkit-text-size-adjust: none. - Event properties: normalize
pageX/Yvsx/y. - Custom attributes: always use
getAttribute().
LESS Mixin Example
.rounded(@radius: 5px) {
border-radius: @radius;
-webkit-border-radius: @radius;
-moz-border-radius: @radius;
}
.button { .rounded(7px); }
Transform: Translate and Scale
.move-scale {
transform: translateX(100px) scale(2);
}
CSS Animation Methods
- Transitions: animate property changes over time (
transition: opacity 0.3s). - Keyframe animations: define complex sequences (
@keyframes,animationproperty).
CSS Preprocessors
Tools like Sass, Less, and Stylus add variables, nesting, mixins, and functions to improve maintainability and modularity.
CSS Modularization
Approaches:
- Preprocessors (Sass/Less modules).
- Build tools (Webpack with CSS loaders).
- PostCSS plugins (
postcss-import,precss).
Whitespace Between List Items
Caused by inline whitespace in HTML. Solutions:
- Parent
font-size: 0. - Negative
margin. - Remove spaces/tabs between
<li>tags.
Progressive Enhancement vs Graceful Degradation
- Progressive Enhancement: build core functionality for all browsers, then enhance for modern ones.
- Graceful Degradation: build for modern browsers, then ensure basic functionality in older ones.
Vendor prefixes should be ordered from most specific (-webkit-) to standard (transition).
CSS Sprites
Combine multiple images into one sprite sheet. Use background-image, background-position, and background-repeat: no-repeat to show specific icons. Reduces HTTP requests.
Mobile Viewport Meta Tag
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
Prevents zooming and sets layout width to device width.
Common CSS Hacks
- Image gaps:
img { display: block; }. - IE6 min-height:
font-size: 0oroverflow: hidden. - Form inconsistencies:
float: left, reset borders. - Cursor:
cursor: pointerfor clickable elements. - Staircase links in IE:
a { display: inline-block; }or float parent<li>.