Section A – CSS Fundamentals
Note: This section introduces the core building blocks of how CSS works — including syntax, rules, and how style declarations are applied to HTML elements.
- A.1 – CSS Syntax: Format of CSS:
selector { property: value; }
- A.2 – Declaration: A single
property: value;
pair. - A.3 – Declaration Block: A group of one or more declarations inside
{ }
. - A.4 – Rule Set: A selector with its declaration block.
- A.5 – Comments: Notes in code using
/* comment */
. - A.6 – Inline CSS: Styling directly on an element via
style=""
attribute. - A.7 – Internal CSS: CSS in a
<style>
tag in the HTML<head>
. - A.8 – External CSS: CSS in a separate file linked with
<link href="style.css">
. - A.9 – Cascade: Defines how conflicts in CSS declarations are resolved based on origin, specificity, and order.
- A.10 – Inheritance: Some properties pass down from parent to child elements automatically.
- A.11 – Specificity: Determines which rule takes precedence when multiple selectors apply.
Section B – Selectors
Note: Selectors are patterns used to target HTML elements and apply styles.
- B.1 – Universal Selector (
*
): Matches any element. - B.2 – Type Selector (
div
): Selects elements by tag name. - B.3 – Class Selector (
.class
): Selects elements with a matching class. - B.4 – ID Selector (
#id
): Selects the unique element with that ID. - B.5 – Grouping Selectors (
h1, p
): Applies styles to multiple selectors at once. - B.6 – Attribute Selector (
[type="text"]
): Targets elements with specific attributes or values. - B.7 – Descendant Combinator (
A B
): Selects element B inside element A (nested structure). - B.8 – Child Combinator (
A > B
): Selects direct children B of parent A. - B.9 – Adjacent Sibling Combinator (
A + B
): Selects element B immediately after A. - B.10 – General Sibling Combinator (
A ~ B
): Selects all B siblings after A. - B.11 – Pseudo-Classes (
:hover
): Target elements based on state (e.g., hover, focus, checked). - B.12 – Structural Pseudo-Classes (
:nth-child(2n)
): Target elements by position or type. - B.13 – Pseudo-Elements (
::before
,::after
): Style generated content before/after elements. - B.14 – Interactive States: Includes
:focus
,:disabled
,:checked
, etc.
Section C – Box Model
Note: Every HTML element is a rectangular box composed of content, padding, border, and margin. This section explains how layout space is calculated and adjusted using the box model.
- C.1 – Content: The innermost box that holds text or other elements.
- C.2 – Padding: Space between the content and the border. It increases the visual spacing inside the element.
- C.3 – Border: The edge around the padding. You can set width, style, and color.
- C.4 – Margin: Space outside the border, separating the element from others.
- C.5 – Box-Sizing (
content-box
vsborder-box
): Determines whether width/height includes padding and border. - C.6 – Collapsing Margins: When vertical margins of adjacent blocks merge into a single margin.
- C.7 – Outline (Non-box Model): An outline that does not affect box size (used for focus/accessibility).
Section D – Display & Positioning
Note: This section explains how elements behave in the layout flow using display
and how to explicitly control their location using the position
property and offsets.
- D.1 – Display Property: Defines layout behavior. Common values include:
block
: Element starts on a new line and stretches to full width.inline
: Stays on the same line without breaking.inline-block
: Like inline but supports width/height.none
: Hides the element completely.
- D.2 – Position Property: Determines how an element is positioned in the document. Values include:
static
: Default. Follows normal flow.relative
: Positioned relative to its normal position.absolute
: Positioned relative to the nearest positioned ancestor.fixed
: Positioned relative to the viewport (always stays visible).sticky
: Toggles between relative and fixed based on scroll.
- D.3 – Top / Right / Bottom / Left: Offset properties used with
position
(except static). - D.4 – Float: Moves elements to the left or right. Removed from normal flow.
- D.5 – Clear: Prevents elements from wrapping around floated elements.
- D.6 – Visibility vs Display:
visibility: hidden
hides the element but preserves its space.
Section E – Flexbox
Note: Flexbox is a one-dimensional layout system that allows elements to align and distribute space within a container along a single axis (row or column).
- E.1 – display: flex; Turns a container into a flex context.
- E.2 – flex-direction: Defines the main axis direction. Values:
row
(default),row-reverse
,column
,column-reverse
- E.3 – justify-content: Aligns items along the main axis. Values:
flex-start
,center
,flex-end
,space-between
,space-around
,space-evenly
- E.4 – align-items: Aligns items along the cross axis. Values:
stretch
(default),flex-start
,center
,flex-end
,baseline
- E.5 – align-self: Overrides
align-items
for a specific item. - E.6 – flex-wrap: Allows items to wrap onto multiple lines. Values:
nowrap
,wrap
,wrap-reverse
- E.7 – align-content: Controls space between wrapped lines on the cross axis.
- E.8 – gap: Defines spacing between rows and columns.
- E.9 – flex-grow: Defines how much an item should grow relative to others.
- E.10 – flex-shrink: Defines how items shrink when space is tight.
- E.11 – flex-basis: Sets the initial size before growing/shrinking.
- E.12 – flex (shorthand): Combines
flex-grow
,flex-shrink
, andflex-basis
(e.g.,flex: 1 1 auto
). - E.13 – order: Controls display order regardless of DOM order.
Section F – Grid
Note: CSS Grid enables two-dimensional layouts, allowing you to control both rows and columns in a container. It is powerful for creating complex web layouts.
- F.1 – display: grid; Defines a grid container and establishes a new grid formatting context.
- F.2 – grid-template-columns: Defines the number and size of columns (e.g.,
200px 1fr 2fr
). - F.3 – grid-template-rows: Defines the number and size of rows.
- F.4 – grid-template: Shorthand for
grid-template-rows
andgrid-template-columns
. - F.5 – grid-column: Specifies the horizontal position of an item (e.g.,
grid-column: 1 / 3
). - F.6 – grid-row: Specifies the vertical position of an item.
- F.7 – grid-area: Name and place grid items using template areas or coordinates.
- F.8 – grid-template-areas: Define layout regions using named strings.
- F.9 – grid-auto-rows / grid-auto-columns: Sets size for rows/columns created implicitly.
- F.10 – grid-auto-flow: Controls direction of auto-placement (
row
,column
, ordense
). - F.11 – gap / row-gap / column-gap: Controls spacing between tracks.
- F.12 – justify-items: Aligns items horizontally in their grid cell.
- F.13 – align-items: Aligns items vertically in their grid cell.
- F.14 – place-items: Shorthand for
align-items
andjustify-items
. - F.15 – justify-content: Aligns the grid container’s content horizontally.
- F.16 – align-content: Aligns the grid container’s content vertically.
- F.17 – place-content: Shorthand for
align-content
andjustify-content
. - F.18 – minmax(): Defines a size range using
minmax(min, max)
. - F.19 – repeat(): Repeats track definitions (e.g.,
repeat(3, 1fr)
). - F.20 – auto-fit / auto-fill: Responsive column behavior with
repeat()
(e.g.,repeat(auto-fit, minmax(200px, 1fr))
).
Section G – Typography
Note: This section covers how to control fonts, sizes, spacing, alignment, decoration, and other properties that affect text appearance.
- G.1 – font-family: Sets the typeface used (e.g.,
font-family: Arial, sans-serif;
). - G.2 – font-size: Controls the size of text (e.g.,
16px
,1rem
). - G.3 – font-weight: Sets boldness (e.g.,
normal
,bold
,100–900
). - G.4 – font-style: Defines italic or oblique styles.
- G.5 – font-variant: Used for small-caps and other typographic variants.
- G.6 – font: Shorthand for setting font properties (e.g.,
font: italic bold 16px/1.5 Arial;
). - G.7 – line-height: Sets spacing between lines of text.
- G.8 – letter-spacing: Adjusts horizontal spacing between characters.
- G.9 – word-spacing: Adjusts spacing between words.
- G.10 – text-align: Aligns text (
left
,right
,center
,justify
). - G.11 – text-indent: Indents the first line of a block.
- G.12 – text-transform: Controls capitalization (
uppercase
,lowercase
,capitalize
). - G.13 – white-space: Controls how white space is handled (e.g.,
nowrap
,pre
). - G.14 – direction: Sets text direction (
ltr
,rtl
). - G.15 – unicode-bidi: Manages complex text direction scenarios.
- G.16 – writing-mode: Controls vertical vs horizontal text flow (
horizontal-tb
,vertical-rl
). - G.17 – text-decoration: Adds lines (underline, overline, line-through).
- G.18 – text-decoration-line / style / color / thickness: Fine-grained control of decoration appearance.
- G.19 – text-shadow: Applies shadow effects to text.
- G.20 – overflow-wrap (word-wrap): Allows breaking long words at the edge of a container.
Section H – Colors
Note: CSS provides multiple ways to define and manipulate color, including named keywords, hexadecimal, RGB(A), HSL(A), and modern color spaces like LAB and LCH.
- H.1 – color: Sets the text color of an element.
- H.2 – background-color: Sets the background fill color.
- H.3 – border-color: Defines the color of an element’s border.
- H.4 – Named Colors: Use color keywords (e.g.,
red
,blue
,rebeccapurple
). - H.5 – Hexadecimal: Color using hex codes like
#FF5733
or shorthand#333
. - H.6 – RGB: Define colors with
rgb(red, green, blue)
where values are 0–255. - H.7 – RGBA: Adds transparency with
rgba(red, green, blue, alpha)
where alpha is 0–1. - H.8 – HSL: Define using
hsl(hue, saturation%, lightness%)
. - H.9 – HSLA: Adds alpha transparency to HSL colors.
- H.10 – currentColor: Inherits the element’s computed text color.
- H.11 – transparent: Fully transparent color (equivalent to
rgba(0,0,0,0)
). - H.12 – opacity: Controls transparency of the whole element (not just color).
- H.13 – color-mix(): Mixes two colors together (e.g.,
color-mix(in srgb, red 50%, blue)
). - H.14 – Modern Color Spaces:
lab()
,lch()
, andoklab()
for better perceptual accuracy. - H.15 – forced-color-adjust: Controls how an element behaves in high contrast mode.
Section I – Units & Values
Note: CSS uses units to express length, time, angle, and more. This section details unit types and common value formats used in style declarations.
- I.1 – Absolute Length Units: Fixed units that do not scale:
px
– Pixelspt
– Points (1/72 of an inch)cm
,mm
– Centimeters, millimetersin
– Inchespc
– Picas (1pc = 12pt)
- I.2 – Relative Length Units: Scale based on context:
em
– Relative to the element's font-sizerem
– Relative to the root font-size%
– Percentage of parent valuevw
,vh
– Viewport width/heightvmin
,vmax
– Smaller/larger of vw and vhex
,ch
– x-height and 0-width of font
- I.3 – Time Units: For animations and transitions:
s
– Secondsms
– Milliseconds
- I.4 – Angle Units: For rotation and gradients:
deg
– Degreesrad
– Radiansgrad
– Gradiansturn
– Full turns
- I.5 – Resolution Units: For media queries:
dpi
– Dots per inchdpcm
– Dots per cmdppx
– Dots per pixel
- I.6 – Frequency Units: Rare, for aural styles:
Hz
,kHz
- I.7 – CSS Keywords (Special Values):
auto
– Automatically computedinitial
– Resets to defaultinherit
– Inherit from parentunset
– Resets based on inheritance rulesrevert
– Reverts to user-agent style
- I.8 – calc(): Combines units with math (e.g.,
width: calc(100% - 2rem)
). - I.9 – clamp(): Sets min, ideal, and max values (e.g.,
clamp(1rem, 2vw, 2rem)
). - I.10 – min() / max(): Returns the smallest or largest of supplied values.
Section J – Backgrounds
Note: CSS backgrounds define the fill behind an element’s content and can include color, images, gradients, and layered effects.
- J.1 – background-color: Sets the background color.
- J.2 – background-image: Applies one or more images (e.g.,
url('image.png')
). - J.3 – background-repeat: Controls tiling behavior:
repeat
,repeat-x
,repeat-y
,no-repeat
- J.4 – background-position: Sets starting position (e.g.,
top left
,center
). - J.5 – background-size: Defines image scaling:
auto
,cover
,contain
, or custom values (e.g.,100% 50%
)
- J.6 – background-attachment: Controls scroll behavior:
scroll
,fixed
,local
- J.7 – background-clip: Defines painting area:
border-box
,padding-box
,content-box
- J.8 – background-origin: Sets positioning reference box:
border-box
,padding-box
,content-box
- J.9 – background-blend-mode: Blends background layers (e.g.,
multiply
,screen
,overlay
). - J.10 – background (shorthand): Combines multiple background properties into one line.
- J.11 – Multiple Background Layers: Use commas to define stacked images or effects (e.g.,
url(a), url(b)
). - J.12 – Gradients: Supported as background-image:
linear-gradient()
,radial-gradient()
,conic-gradient()
Section K – Borders & Outlines
Note: Borders form part of the element box and control thickness, color, and style. Outlines are external indicators, useful for accessibility and focus states.
- K.1 – border-width: Sets the thickness of the border on all sides.
- K.2 – border-style: Defines the line style (e.g.,
solid
,dashed
,dotted
,double
,none
). - K.3 – border-color: Sets the color of the border.
- K.4 – border: Shorthand for width, style, and color (e.g.,
1px solid black
). - K.5 – border-top / right / bottom / left: Individual side borders.
- K.6 – border-radius: Rounds the corners of the element box (e.g.,
border-radius: 8px
). - K.7 – outline: Draws a line outside the element box; does not affect layout.
- K.8 – outline-width: Thickness of the outline.
- K.9 – outline-style: Line style of the outline (same as border-style options).
- K.10 – outline-color: Color of the outline.
- K.11 – outline-offset: Distance between outline and border edge.
- K.12 – border-collapse (tables): Controls border merging in tables (
collapse
vsseparate
). - K.13 – border-spacing (tables): Sets space between table cell borders when separated.
Section L – Sizing
Note: CSS sizing properties allow control over the rendered dimensions of elements, including width, height, and constraints like min/max values.
- L.1 – width: Sets the element's horizontal dimension (e.g.,
width: 200px
). - L.2 – height: Sets the element’s vertical dimension.
- L.3 – min-width / min-height: Defines the minimum size an element can shrink to.
- L.4 – max-width / max-height: Defines the maximum size an element can grow to.
- L.5 – auto: Allows the browser to calculate size based on content or layout context.
- L.6 – fit-content: Fits to the content’s intrinsic size (with limits).
- L.7 – max-content: Element grows to fit longest unbreakable content.
- L.8 – min-content: Shrinks to smallest size without overflow.
- L.9 – intrinsic sizing keywords: Uses
min-content
,max-content
,fit-content
to define size behavior. - L.10 – aspect-ratio: Sets or locks an element’s width-to-height ratio (e.g.,
aspect-ratio: 16 / 9
). - L.11 – box-sizing: Affects how width and height include padding/border:
content-box
– Width excludes padding/borderborder-box
– Width includes padding/border
- L.12 – inline-size / block-size: Logical (writing-mode aware) sizing alternatives for width/height.
Section M – Spacing
Note: CSS spacing properties control both internal space (padding) and external space (margin) around elements. Logical spacing respects writing direction.
- M.1 – margin: Creates space outside an element's border (e.g.,
margin: 16px
). - M.2 – margin-top / right / bottom / left: Sets margins on individual sides.
- M.3 – margin (shorthand): Supports up to 4 values (top, right, bottom, left).
- M.4 – margin: auto: Enables automatic centering in block layout.
- M.5 – padding: Creates space between content and border.
- M.6 – padding-top / right / bottom / left: Sets padding per side.
- M.7 – padding (shorthand): Accepts up to 4 values like margin shorthand.
- M.8 – logical margin & padding: Writing-mode aware alternatives:
margin-inline-start
,margin-block-end
padding-inline
,padding-block
- M.9 – negative margins: Pull elements closer by setting
margin: -value
. - M.10 – margin collapse: Vertical margins of adjacent blocks may collapse into one.
Section N – Layout Strategies
Note: CSS layout strategies provide ways to arrange elements on the page using different models like block, flexbox, grid, and absolute positioning. Choosing the right strategy is key for responsive, maintainable layouts.
- N.1 – Block Layout (Normal Flow): Default layout behavior for block-level and inline elements.
- N.2 – Flex Layout: One-dimensional layout with alignment and distribution (see Section E).
- N.3 – Grid Layout: Two-dimensional layout with explicit row/column control (see Section F).
- N.4 – Positioning Layout: Uses
position: absolute/fixed/relative/sticky
to take elements out of flow or adjust their stack. - N.5 – Float Layout: Legacy layout using
float
andclear
(not recommended for main structure). - N.6 – Table Layout: Simulates HTML tables using
display: table
,table-row
, etc. - N.7 – Multi-column Layout: Creates newspaper-style columns using
column-count
andcolumn-gap
. - N.8 – Container Queries: Allows layout behavior based on parent container’s size (see Section AG).
- N.9 – Responsive Design: Combines units like %, vw/vh, media queries, flex/grid, and content-aware sizing for cross-device layouts.
- N.10 – Intrinsic Layouts: Use content-based sizing strategies with
min-content
,max-content
, andauto
. - N.11 – Layered Layout (z-index): Uses stacking contexts and z-index for visual layering (see Section T).
- N.12 – Isolation: Uses
isolation: isolate
to create new stacking contexts when needed.
Section O – Media Queries
Note: Media queries apply conditional CSS rules depending on the viewport or device. They're essential for creating responsive and accessible designs.
- O.1 – Basic Syntax:
@media (condition) { selector { property: value; } }
- O.2 – Common Features:
min-width
/max-width
min-height
/max-height
orientation
:portrait
orlandscape
resolution
: e.g.,300dpi
aspect-ratio
: e.g.,16/9
hover
: Whether the user can hover with inputpointer
: e.g.,fine
,coarse
- O.3 – Example (min-width):
@media (min-width: 768px) { body { font-size: 18px; } }
- O.4 – Combining Conditions: Use
and
,not
,only
:@media only screen and (min-width: 1024px)
@media not print
- O.5 – Media Types:
screen
,print
,speech
,all
- O.6 – Range Contexts: New syntax:
(width > 400px)
,(300px <= width <= 800px)
- O.7 – Media Query Shorthand (Level 4): Advanced form:
@media (width >= 768px)
- O.8 – prefers-color-scheme: Detects dark/light mode preference.
- O.9 – prefers-reduced-motion: Respects user's motion reduction settings.
- O.10 – Responsive Utility: Combine media queries with flex/grid for full responsiveness.
Section P – Transforms
Note: CSS transforms let you manipulate elements in 2D or 3D space. Transformed elements remain in the same flow but can be visually moved, rotated, scaled, or skewed.
- P.1 – transform (shorthand): Applies multiple transform functions together.
transform: rotate(45deg) scale(1.2);
- P.2 – translate(x, y): Moves the element along the X and Y axes.
translateX(50px)
translateY(-20%)
- P.3 – scale(x, y): Resizes the element.
scale(1.5)
– Enlargesscale(0.8)
– ShrinksscaleX()
,scaleY()
- P.4 – rotate(angle): Rotates the element (e.g.,
rotate(45deg)
,rotate(-0.25turn)
). - P.5 – skew(x, y): Shears the element along the X and/or Y axis.
skewX(20deg)
,skewY(-10deg)
- P.6 – matrix(a, b, c, d, e, f): Applies all transform functions using a transformation matrix (advanced).
- P.7 – transform-origin: Sets the point around which transforms are applied (e.g.,
center
,top left
,50% 100%
). - P.8 – transform-box: Affects the bounding box used for transforms (e.g.,
fill-box
,border-box
). - P.9 – perspective: Defines depth for 3D transforms.
- P.10 – backface-visibility: Controls whether the back side of a transformed element is visible.
- P.11 – 3D Transforms:
rotateX()
,rotateY()
,rotateZ()
translateZ()
,scaleZ()
perspective()
,transform-style: preserve-3d
Section Q – Transitions & Animations
Note: CSS transitions animate changes between property values, while animations allow control over multiple stages via keyframes.
- Q.1 – transition-property: Specifies the CSS property to animate (e.g.,
color
,transform
). - Q.2 – transition-duration: How long the transition lasts (e.g.,
0.5s
,300ms
). - Q.3 – transition-timing-function: Controls acceleration curve (e.g.,
ease
,linear
,ease-in-out
,cubic-bezier()
). - Q.4 – transition-delay: Sets the delay before the transition starts.
- Q.5 – transition (shorthand): Combines all transition properties:
transition: transform 0.3s ease-in-out;
- Q.6 – @keyframes: Defines intermediate steps of an animation:
@keyframes fade { from { opacity: 0; } to { opacity: 1; } }
- Q.7 – animation-name: The keyframes rule to use.
- Q.8 – animation-duration: Total length of one animation cycle.
- Q.9 – animation-timing-function: Acceleration curve (same options as transitions).
- Q.10 – animation-delay: Start delay before the animation begins.
- Q.11 – animation-iteration-count: Number of times to run (e.g.,
infinite
,3
). - Q.12 – animation-direction: Direction of animation (
normal
,reverse
,alternate
). - Q.13 – animation-fill-mode: Defines how styles apply before/after animation (
forwards
,backwards
,both
). - Q.14 – animation-play-state: Allows pausing and resuming animations (
running
,paused
). - Q.15 – animation (shorthand): Combines all animation properties:
animation: fade 2s ease-in-out 0s 1 normal forwards;
Section R – Custom Properties (Variables)
Note: CSS variables allow you to define and reuse consistent values across your stylesheet. They can be scoped to elements and updated dynamically.
- R.1 – Declaration: Custom properties are declared using a name prefixed with
--
::root { --primary-color: #3366ff; }
- R.2 – Usage: Use
var()
to reference a custom property:color: var(--primary-color);
- R.3 – Fallback Values: Provide a default if the variable isn’t defined:
color: var(--accent, #999);
- R.4 – Scope: Custom properties inherit through the DOM tree. You can redefine them on specific elements.
- R.5 – Dynamic Themes: Easily switch themes by overriding root variables (e.g., light/dark mode).
- R.6 – Example – Button Theme:
:root { --btn-bg: #444; --btn-text: #fff; } button { background-color: var(--btn-bg); color: var(--btn-text); }
- R.7 – Invalid Reference: If a variable is missing and no fallback is provided, the property becomes invalid.
- R.8 – calc() + var(): Custom properties can be used inside functions like
calc()
. - R.9 – Performance: Custom properties are resolved at runtime, allowing updates with JavaScript or user settings (without JS here, still useful).
Section S – Pseudo-Classes & Pseudo-Elements
Note: Pseudo-classes target elements based on behavior, position, or user interaction. Pseudo-elements create abstract parts of elements to style or populate.
- S.1 – Pseudo-Classes (User Interaction):
:hover
– When the user hovers the mouse:focus
– When the element is focused:active
– While the element is being clicked:visited
– Visited link:checked
– Checked input/checkbox:disabled
,:enabled
,:read-only
- S.2 – Pseudo-Classes (Structural):
:first-child
,:last-child
:nth-child(n)
,:nth-of-type(n)
:only-child
,:empty
:not(selector)
– Negation pseudo-class
- S.3 – Pseudo-Classes (UI & State):
:required
,:optional
:valid
,:invalid
:in-range
,:out-of-range
:target
– Matches the target of the current URL hash
- S.4 – Pseudo-Elements:
::before
– Inserts content before an element::after
– Inserts content after an element::first-letter
,::first-line
::selection
– Styles highlighted text::placeholder
– Styles input placeholder text::marker
– List item bullets
- S.5 – Content with ::before/::after:
p::before { content: "→ "; color: red; }
- S.6 – Combined Use: You can combine pseudo-classes and pseudo-elements:
a:hover::after { content: " (external)"; }
Section T – Z-Index & Stacking
Note: The `z-index` property determines the stack order of elements along the Z axis. Higher values appear on top. Only works on positioned or flex/grid children.
- T.1 – z-index: Controls stack level (e.g.,
z-index: 10;
). Higher values appear above lower ones. - T.2 – Prerequisite – Positioning: Only elements with
position: relative
,absolute
,fixed
, orsticky
participate in `z-index` stacking. - T.3 – Auto (default): Inherits stacking order from parent or natural order of appearance.
- T.4 – Stacking Contexts: New stacking contexts are created by:
- Positioned elements with `z-index`
- Elements with `opacity` less than 1
- CSS properties like `transform`, `filter`, `perspective`, `isolation: isolate`, `will-change`
- Flex/grid children with `z-index`
- T.5 – Nested Stacking: `z-index` only affects siblings within the same stacking context.
- T.6 – Overlap Behavior: Later elements in the HTML stack above earlier ones if `z-index` is equal or `auto`.
- T.7 – Practical Tip: Avoid high arbitrary values. Instead, control layering through clear hierarchy and component isolation.
- T.8 – Example:
.box1 { position: absolute; z-index: 1; } .box2 { position: absolute; z-index: 5; }
- T.9 – isolation: Use
isolation: isolate;
to create a new stacking context deliberately. - T.10 – Debugging Tools: Use browser dev tools to inspect stacking contexts visually.
Section U – Overflow & Clipping
Note: CSS overflow controls whether content that exceeds its container is visible, hidden, clipped, or scrollable. Clipping provides finer control over visible regions.
- U.1 – overflow: Applies to both axes:
visible
– Content spills out (default)hidden
– Overflow is clipped, no scrollscroll
– Always shows scrollbarsauto
– Scrollbars appear only when needed
- U.2 – overflow-x / overflow-y: Sets overflow independently for horizontal and vertical axes.
- U.3 – text-overflow: Controls behavior of clipped inline text (e.g.,
ellipsis
).white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
- U.4 – clip-path: Defines a visible region of an element using shapes or paths:
circle()
,ellipse()
,polygon()
,inset()
- U.5 – clip: Deprecated property used with
position: absolute
; replaced by `clip-path`. - U.6 – scroll-behavior: Enables smooth or instant scrolling behavior.
html { scroll-behavior: smooth; }
- U.7 – overflow-anchor: Prevents scroll position jumps when content updates dynamically.
- U.8 – overflow-wrap (word-wrap): Allows breaking long words within content.
normal
,break-word
- U.9 – white-space: Controls how whitespace is handled (e.g.,
nowrap
,pre
,pre-wrap
). - U.10 – contain: layout / paint: Ensures an element does not affect outside layout or paint, often used with overflow containment.
Section V – Visibility & Opacity
Note: These properties control whether an element is visible, how it participates in layout, and its visual transparency without affecting DOM structure.
- V.1 – visibility: Toggles element visibility while preserving layout space.
visible
– Element is shown (default)hidden
– Element is invisible but still takes up spacecollapse
– For table rows/cells only; hides without space
- V.2 – display: none: Completely removes element from layout and rendering.
- V.3 – opacity: Controls transparency level from 0 (fully transparent) to 1 (fully opaque).
opacity: 0.5;
- V.4 – pointer-events: Controls whether the element can receive mouse/pointer events.
pointer-events: none;
– Disables interactionpointer-events: auto;
– Enables default behavior
- V.5 – user-select: Determines if content is selectable.
none
,text
,all
- V.6 – visibility vs display:
visibility: hidden
keeps layout space;display: none
removes it entirely. - V.7 – accessibility note: Hidden elements (via `display: none` or `visibility: hidden`) are not read by screen readers unless managed carefully with ARIA.
Section W – Cursors & User Interaction
Note: These properties define how the pointer appears when hovered over an element, and whether users can interact or select its content.
- W.1 – cursor: Changes the mouse pointer type.
pointer
– Hand (for links/buttons)default
– Arrowtext
– I-beam for text fieldsmove
,grab
,grabbing
crosshair
,help
,wait
,progress
not-allowed
,no-drop
,none
url(custom.cur), auto
– Use custom image cursor
- W.2 – pointer-events: Enables/disables click or hover on elements.
none
– Element is invisible to the pointerauto
– Default interaction behavior
- W.3 – user-select: Determines whether text or elements can be selected by the user.
none
,text
,all
,auto
- W.4 – touch-action: Controls how touch devices handle gestures on an element.
none
– Prevent all gesturesmanipulation
– Allows scroll, pinch, etc.
- W.5 – caret-color: Changes the blinking cursor color in inputs and editable elements.
- W.6 – outline-style: Controls keyboard focus visibility (e.g., tab navigation).
- W.7 – :focus-visible: Targets keyboard-only focus, avoiding focus rings for mouse clicks.
- W.8 – Disabled States: Use
:disabled
to style and restrict user interaction.
Section X – Print Styles
Note: CSS print styles ensure documents are formatted correctly when printed, removing unnecessary elements and managing layout breaks across pages.
- X.1 – @media print: Target print-specific styles using a media query:
@media print { body { font-size: 12pt; color: black; } }
- X.2 – Hiding Non-Print Elements: Prevent certain elements (e.g., nav, ads) from appearing in print:
@media print { .no-print { display: none; } }
- X.3 – Forcing Page Breaks: Use page-break properties to control content flow:
page-break-before: always;
page-break-after: avoid;
break-inside: avoid;
– Prevents breaking within elements like tables or images
- X.4 – @page: Define global page setup for size and margins:
@page { size: A4; margin: 1in; }
- X.5 – Print Colors: Use print-safe color contrasts (avoid neon/transparencies) and ensure high contrast for accessibility.
- X.6 – Font Considerations: Use system fonts or include fallback for better print consistency.
- X.7 – Links in Print: Use pseudo-elements to print full URLs:
a::after { content: " (" attr(href) ")"; }
- X.8 – Avoid Fixed Heights/Widths: Let content flow naturally for different paper sizes.
- X.9 – Common Print Targets:
header
,main
,article
,footer
,figure
- X.10 – Page-Break Shorthand (New):
break-before
,break-after
,break-inside
now replace `page-break-*` (deprecated).
Section Y – Accessibility (A11y)
Note: While semantic HTML is key for accessibility, CSS can assist with focus visibility, motion control, color contrast, and screen reader-friendly practices.
- Y.1 – focus-visible: Highlights focused elements only when keyboard is used:
button:focus-visible { outline: 2px solid #005fcc; }
- Y.2 – outline vs border: Use
outline
for focus styles so it doesn't shift layout likeborder
. - Y.3 – prefers-reduced-motion: Respect user settings to reduce animation:
@media (prefers-reduced-motion: reduce) { * { animation: none !important; transition: none !important; } }
- Y.4 – visually-hidden (screen reader only):
.sr-only { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; border: 0; clip: rect(0 0 0 0); overflow: hidden; white-space: nowrap; }
This hides content visually while keeping it accessible to screen readers.
- Y.5 – high contrast support: Avoid low-contrast color combinations; test for at least 4.5:1 contrast ratio for normal text.
- Y.6 – forced colors mode (Windows): Add support with
@media (forced-colors: active)
. - Y.7 – font-size units: Use relative units like
em
,rem
for scalable text. - Y.8 – text spacing guidelines: Avoid text overlapping when user increases spacing settings (see WCAG 2.1 success criterion 1.4.12).
- Y.9 – focus order management: Do not change visual order with CSS (e.g.,
order
in flexbox) unless it matches DOM reading order. - Y.10 – aria-hidden: Use HTML's
aria-hidden="true"
for elements styled as hidden to assist screen readers.
Section Z – Shorthand Properties
Note: Shorthand properties group related CSS properties into a single declaration, reducing repetition and improving maintainability. However, omitted values reset to their defaults.
- Z.1 – margin / padding:
margin: 10px 20px 30px 40px; /* top right bottom left */
- Z.2 – border:
border: 1px solid #333;
- Z.3 – font:
font: italic small-caps 700 16px/1.5 'Roboto', sans-serif;
⚠ Must include
font-size
andfont-family
to be valid. - Z.4 – background:
background: #000 url(bg.png) no-repeat center/cover;
- Z.5 – transition:
transition: all 0.3s ease-in-out;
- Z.6 – animation:
animation: fadeIn 2s ease-out 0s 1 normal both;
- Z.7 – outline:
outline: 2px dotted red;
- Z.8 – flex-flow: Combines
flex-direction
andflex-wrap
flex-flow: row wrap;
- Z.9 – grid-area: Combines
grid-row-start
,grid-column-start
, etc.grid-area: 1 / 2 / 3 / 4;
- Z.10 – list-style:
list-style: square inside;
- Z.11 – border-radius: Can be written for 1–4 corners.
border-radius: 8px 12px 4px 0;
- Z.12 – columns: Combines
column-width
andcolumn-count
columns: 2 200px;
- Z.13 – overflow:
overflow: hidden auto; /* x y */
- Z.14 – inset: Combines
top
,right
,bottom
, andleft
inset: 10px 15px 5px 0;
Section AA – Best Practices
Note: These are established techniques for writing clean, robust, and forward-compatible CSS in production environments.
- AA.1 – Use semantic HTML + class-based styling: Keep HTML meaning intact and style via classes instead of tag selectors where possible.
- AA.2 – Organize styles logically: Group rules by component or layout section (e.g., header, nav, footer).
- AA.3 – Use a naming convention: Adopt BEM, SMACSS, or custom pattern to avoid conflicts and improve readability.
- AA.4 – Prefer utility classes for spacing/layout: Abstract repetitive spacing with atomic utility classes (e.g.,
.mt-4
). - AA.5 – Avoid !important (except for overrides): Use specificity and structure to resolve conflicts without needing
!important
. - AA.6 – Use custom properties (variables): Define and reuse colors, spacing, font sizes consistently across the stylesheet.
- AA.7 – Set a CSS reset or normalize baseline: Start with a consistent cross-browser style baseline (e.g., Normalize.css or a reset block).
- AA.8 – Use relative units (em/rem/%): Make text and layouts scalable and accessible across devices and screen sizes.
- AA.9 – Limit nesting: Deep nesting increases specificity and reduces readability. Keep selectors shallow when possible.
- AA.10 – Minimize overrides: Architect CSS to avoid needing to undo or overwrite styles later.
- AA.11 – Comment critical sections: Explain decisions, caveats, or hacks to help others (or your future self).
- AA.12 – Test across browsers and devices: Validate CSS works consistently using tools like BrowserStack or real devices.
- AA.13 – Use dev tools for inspection: Use browser developer tools to debug layout, styles, stacking, and state changes.
- AA.14 – Keep CSS modular: Use external stylesheets per component or page section in large projects.
- AA.15 – Automate formatting: Use Prettier or Stylelint to enforce consistent code formatting and avoid errors.
Section AB – Common Pitfalls
Note: These are mistakes developers often make when writing CSS. Understanding them helps avoid bugs, layout inconsistencies, and accessibility issues.
- AB.1 – Overusing !important: Leads to specificity chaos and override wars. Reserve for critical overrides only.
- AB.2 – Not understanding specificity: Conflicts arise when selectors compete. Learn how ID, class, and element specificity stacks.
- AB.3 – Deeply nested selectors: Reduces reusability, increases specificity, and leads to brittle code.
- AB.4 – Using fixed units everywhere: Avoid rigid
px
sizing for text/layouts. Userem
,em
, or percentages for responsiveness. - AB.5 – Setting width/height without box-sizing: Leads to unexpected overflow. Use
box-sizing: border-box;
. - AB.6 – Not using a reset or normalize: Default browser styles vary. Normalize creates consistency across environments.
- AB.7 – Styling via tag names only: Overwrites all instances and can break third-party components. Use classes instead.
- AB.8 – Improper z-index usage: Failing to understand stacking contexts causes elements not to layer as expected.
- AB.9 – Relying on float for layout: Float is outdated. Prefer Flexbox or Grid for layout structures.
- AB.10 – Inconsistent naming conventions: Makes styles hard to trace or debug. Adopt a system (e.g., BEM, SMACSS).
- AB.11 – No accessibility consideration: Visual-only design without semantic structure or focus states harms usability.
- AB.12 – Ignoring responsive design: Fixed widths break layouts on mobile. Use media queries and fluid units.
- AB.13 – Animating layout properties: Avoid transitions on
top
,left
,width
, etc. — usetransform
for better performance. - AB.14 – Missing fallbacks for custom properties: Use fallbacks when supporting older browsers:
color: black; color: var(--text-color, black);
- AB.15 – Unused or duplicate rules: Bloats CSS. Use audits and cleanup tools regularly.
Section AC – Debugging Tools
Note: Debugging CSS effectively requires visual inspection, layout tracing, and clear indicators of how styles are applied and inherited.
- AC.1 – Browser DevTools: Use Chrome, Firefox, Safari, or Edge inspector panels to:
- Inspect elements and computed styles
- Edit CSS in real time
- View box model overlays
- Check accessibility, color contrast, and ARIA attributes
- AC.2 – Element outlines for layout tracing:
* { outline: 1px solid red !important; }
Use this globally to highlight every element boundary.
- AC.3 – Debug utility classes: Apply temporary debug classes to spot-check structure:
.debug { background: rgba(255,0,0,0.1); border: 1px dashed red; }
- AC.4 – Isolation helpers: Use
isolation: isolate
oroverflow: hidden
to isolate stacking/debug z-index conflicts. - AC.5 – Layout overlays in DevTools: Toggle CSS Grid/Flexbox overlays in most browsers to see gaps, flow, and alignment.
- AC.6 – Scroll overflow indicators: Use overflow tests to spot scroll or clipping issues:
body { overflow: auto; }
- AC.7 – Responsive Design Mode: Test breakpoints visually in your browser’s dev tools.
- AC.8 – Performance panel: Evaluate style recalculations, reflows, and expensive animations.
- AC.9 – Use computed tab: Analyze final cascade and overrides to determine why a property isn’t applied.
- AC.10 – Style audit extensions: Install tools like:
- Lighthouse (Chrome)
- axe DevTools (accessibility)
- VisBug (interactive inspection)
- AC.11 – Avoid permanent debug styles: Remove helper styles before deployment to avoid bloated or broken UI.
Section AD – Cheat Sheet Structure
Note: This section explains the foundational layout, code organization, and logic behind building the cheat sheet for consistent long-term scalability.
- AD.1 – HTML Semantics: Each cheat sheet section is wrapped in a semantic
<section>
element with a heading (`<h2>`). - AD.2 – Section Class Naming: All section containers use a shared class
.section
for unified layout control. - AD.3 – Headings Structure:
h2
for primary section titles (A–Z)h3
or list items for subsection labels (e.g., A.1, B.2, etc.)
- AD.4 – Code Examples: Use semantic tags:
<pre><code>
for blocks and<code>
inline. Always escape angle brackets. - AD.5 – Inline Notes: Use
<em>
for short parenthetical or cautionary notes within paragraphs. - AD.6 – Descriptive Comments: Every section starts with a `` comment and a 1-line purpose summary.
- AD.7 – Alphabetical Section IDs: Keep track of sections by using IDs or anchors like `id="section-a"` if needed for TOC.
- AD.8 – File Separation: Cheat sheet is split into:
- index.html – Content and structure
- styles.css – Layout, color, spacing, and theme styling
- AD.9 – Expandability: Every section is modular and can be appended without disrupting layout.
- AD.10 – Table of Contents: A persistent or collapsible table of contents can link directly to each section (optional).
- AD.11 – Code Consistency: Use consistent casing (e.g., kebab-case for classes, lowercase for HTML tags, no inline styles).
- AD.12 – Accessibility in Markup: Follow WCAG: semantic structure, clear headings, keyboard focusable, contrast safe.
Section AE – Reference Section
Note: This glossary-style section allows quick access to recurring CSS concepts, unit types, common keywords, and external documentation.
- AE.1 – Common Units:
px
– Pixels (absolute)em
– Relative to parent font sizerem
– Relative to root element font size%
– Relative to containing elementvw/vh
– Viewport width/heightch
,ex
– Character/height-basedfr
– Grid fractional unit
- AE.2 – Display Values (Quick List):
block
,inline
,inline-block
flex
,grid
,inline-flex
,inline-grid
none
– Hides element
- AE.3 – Position Values:
static
,relative
,absolute
,fixed
,sticky
- AE.4 – Color Keywords:
red
,black
,white
,transparent
,currentColor
- HEX:
#rrggbb
| RGB:rgb(255, 0, 0)
| HSL:hsl(0, 100%, 50%)
- AE.5 – Common Timing Functions:
ease
,ease-in
,ease-out
,ease-in-out
,linear
,cubic-bezier()
- AE.6 – Z-Index Reference: Determines stacking order; higher number = top layer.
- AE.7 – Specificity Reference: Inline > ID > Class > Type > Universal
(1000: inline, 100: ID, 10: class, 1: element) - AE.8 – Useful External Links:
Section AG – Container Queries
Note: Container Queries allow elements to style themselves based on the width, height, or inline size of their parent. Useful for responsive components and layout blocks.
- AG.1 – Enable a container context: Apply
container-type
to the container element..card { container-type: inline-size; container-name: card; }
- AG.2 – Write a container query:
@container (min-width: 400px) { .card h2 { font-size: 1.5rem; } }
This only applies when the container is at least 400px wide, regardless of the viewport.
- AG.3 – Naming containers (optional): Assign container names with
container-name
and target specific ones.@container card (min-width: 500px) { .card-content { padding: 2rem; } }
- AG.4 – Types of container types:
size
– Queries both inline-size and block-size (rarely supported)inline-size
– Queries horizontal size (most common)normal
– Allows containment only of style/layout
- AG.5 – Nesting behavior: Container queries apply only to direct or nested elements inside the container — not globally like media queries.
- AG.6 – When to use: Use container queries inside reusable components (cards, widgets, blocks) where layout or font scaling needs to adapt **per section**, not per screen.
- AG.7 – Fallback strategy: Use default styles outside queries for basic support, then layer enhancements in
@container
blocks.
Section AH – Environment Variables
Note: Environment variables are accessed using the env()
function. They adjust layout based on device conditions like notches, navigation bars, and system UI constraints.
- AH.1 – Safe area insets (common on mobile):
padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);
Ensures content does not overlap notches or system bars on iOS/Android.
- AH.2 – Example with fallback:
padding-left: env(safe-area-inset-left, 1rem);
If the environment variable is unsupported, fallback to 1rem.
- AH.3 – List of common env() variables:
safe-area-inset-top
safe-area-inset-bottom
safe-area-inset-left
safe-area-inset-right
- AH.4 – Use in fixed headers/footers:
.header { padding-top: env(safe-area-inset-top); }
- AH.5 – Combined with media queries:
@media (orientation: landscape) { .container { padding-left: env(safe-area-inset-left); } }
- AH.6 – Platform use cases: Especially useful in:
- iPhones with notches (X and newer)
- Android immersive mode apps
- Progressive Web Apps (PWAs)
- Edge-to-edge layouts
Section AI – Logical Properties
Note: Logical properties automatically adapt styles based on writing direction (like Arabic or vertical Japanese) and support internationalization better than physical properties like left
or top
.
- AI.1 – Logical vs Physical Comparison:
Physical Logical margin-left
margin-inline-start
margin-right
margin-inline-end
padding-top
padding-block-start
width
inline-size
height
block-size
- AI.2 – Common Logical Properties:
margin-inline
,margin-block
padding-inline
,padding-block
inset-inline
,inset-block
border-inline
,border-block
- AI.3 – Practical Example:
.box { padding-inline: 1rem; padding-block: 0.5rem; border-inline-start: 2px solid red; }
This works correctly whether text is left-to-right or right-to-left.
- AI.4 – Sizing with logical dimensions:
.card { inline-size: 100%; block-size: auto; }
- AI.5 – Writing-mode-aware layout:
html { writing-mode: vertical-rl; }
Combine with logical properties for robust vertical writing support.
- AI.6 – When to use: Always prefer logical properties in:
- Multilingual websites
- Right-to-left support (Arabic, Hebrew)
- Vertical writing (Japanese, Chinese)
- Reusable layout components
Section AJ – Cascade Layers (@layer
)
Note: @layer
introduces a new way to control the cascade — before specificity and order — allowing cleaner overrides between resets, base styles, utilities, and component-specific rules.
- AJ.1 – Declaring layers:
@layer reset, base, components, overrides;
This sets the cascade order of named layers (first wins, last overrides).
- AJ.2 – Defining styles in a layer:
@layer base { h1, h2, h3 { font-family: system-ui; } }
- AJ.3 – Nesting layers inside imports:
@import url('reset.css') layer(reset); @import url('base.css') layer(base);
Useful when layering external stylesheets like resets and frameworks.
- AJ.4 – Overriding in upper layers:
@layer overrides { button { background-color: red; } }
This overrides the same selector defined in earlier layers.
- AJ.5 – Why use @layer:
- Cleanly separates concern domains (reset/base/utilities/components)
- Reduces need for
!important
or specificity battles - Improves readability of CSS override intent
- AJ.6 – How it fits into the cascade:
@layer
sits above selector specificity but below inline styles and!important
. - AJ.7 – Fallback strategy: Layers are ignored in browsers that don’t support them. Use base styles unlayered in fallback sheets if needed.
Section AK – Modern Color Spaces
Note: Use modern color spaces to achieve better contrast, uniform perceptual shifts, and improved accessibility on wide-gamut displays.
- AK.1 –
lab()
:color: lab(50% 20 30);
Perceptual lightness (L) and chroma (a/b axes) — more visually accurate than RGB.
- AK.2 –
lch()
:color: lch(70% 50 320);
Lightness–Chroma–Hue — offers intuitive hue angles and brightness scaling.
- AK.3 –
oklab()
:color: oklab(0.7 0.1 0.1);
Improved lightness linearity and contrast ratios — excellent for accessible UIs.
- AK.4 –
color()
with profile targeting:color: color(display-p3 1 0.5 0);
Target color profiles like
display-p3
,srgb
, orrec2020
. - AK.5 – Color interpolation benefits: Use modern spaces for gradients that preserve tone and contrast:
background: linear-gradient(in oklab, red, blue);
- AK.6 – Color mixing:
color-mix(in lch, red 60%, blue 40%)
Blends colors in perceptual space rather than RGB.
- AK.7 – Fallback strategy:
color: red; /* fallback */ color: lab(55% 30 20);
Browsers that don’t support `lab()` will ignore the second declaration.
- AK.8 – When to use:
- Accessible theming and contrast tuning
- Consistent color transitions and gradients
- UI component theming with perceptual accuracy
Section AL – Scroll Behavior
Note: CSS scroll behavior controls how scrolling transitions occur, including anchor jumps and programmatic scrolling. Use it for a smoother user experience in single-page layouts or in-page navigation.
- AL.1 – Enabling smooth scrolling globally:
html { scroll-behavior: smooth; }
This enables smooth anchor scrolling across the whole document.
- AL.2 – Applying locally to containers:
.scroll-box { overflow: auto; scroll-behavior: smooth; }
Enables smooth scroll inside scrollable divs or modal elements.
- AL.3 – Scroll behavior values:
auto
– Default browser behavior (jump)smooth
– Animates scrolling
- AL.4 – Scroll-margin and scroll-padding:
Used with sticky headers or in-page links to prevent overlap.
h2 { scroll-margin-top: 80px; }
- AL.5 – Scroll snapping (optional):
.container { scroll-snap-type: y mandatory; } .child { scroll-snap-align: start; }
Use for carousels, sections, and full-screen scrollers.
- AL.6 – When to use:
- Anchor navigation (`#section-id` links)
- Scrollable cards or horizontal UIs
- Page layout with sticky headers
Section AM – Aspect Ratio (Deep Dive)
Note: aspect-ratio
maintains a consistent ratio between width and height. Ideal for images, videos, containers, and placeholders in responsive layouts.
- AM.1 – Basic usage:
.box { aspect-ratio: 16 / 9; }
This creates a box that always maintains a 16:9 ratio.
- AM.2 – Square and golden ratio examples:
.square { aspect-ratio: 1 / 1; } .golden { aspect-ratio: 1.618 / 1; }
- AM.3 – Works with
width
,height
, or both unset:If only one dimension is defined, the other is inferred from the ratio.
.responsive { width: 100%; aspect-ratio: 4 / 3; }
- AM.4 – Used in Grid or Flex layouts:
.grid-item { aspect-ratio: 1 / 1; }
Ensures even spacing or consistent card size in dynamic layouts.
- AM.5 – Maintaining aspect ratio on media:
img { width: 100%; height: auto; aspect-ratio: 3 / 2; }
Supports images that lack intrinsic aspect ratios or are dynamically sized.
- AM.6 – Nested use with object-fit:
.image-box { aspect-ratio: 16 / 9; overflow: hidden; } .image-box img { object-fit: cover; width: 100%; height: 100%; }
Used for avatar frames, thumbnails, or video containers.
- AM.7 – Browser support:
Fully supported in all major browsers (Chrome, Edge, Firefox, Safari).
Section AN – Form Styling
Note: Form controls require careful styling for consistency across browsers, accessibility, and responsive layout. CSS enables full control over layout, spacing, colors, focus, and states.
- AN.1 – Basic input and label:
label { display: block; margin-bottom: 0.5rem; font-weight: bold; } input, select, textarea { padding: 0.5rem; border: 1px solid #ccc; border-radius: 4px; width: 100%; }
- AN.2 – Placeholder styling:
::placeholder { color: #888; font-style: italic; }
- AN.3 – Focus states:
input:focus, textarea:focus { outline: 2px solid #0077cc; border-color: #0077cc; }
- AN.4 – Disabled and read-only:
input:disabled { background: #f3f3f3; cursor: not-allowed; opacity: 0.7; }
- AN.5 – Custom checkbox/radio:
Default styles are limited. Use pseudo-elements or appearance reset:
input[type="checkbox"] { accent-color: #0077cc; }
Use
appearance: none;
and custom SVG for full control. - AN.6 – Range sliders and file inputs:
These require vendor-specific pseudo-elements and may be best left minimally styled or replaced with JS-based components.
- AN.7 – Layout with grid/flex:
.form-group { display: flex; flex-direction: column; gap: 0.75rem; }
- AN.8 – Submit buttons:
button[type="submit"] { background: #005fcc; color: white; border: none; padding: 0.75rem 1.25rem; border-radius: 4px; cursor: pointer; } button:hover { background: #0043aa; }
- AN.9 – Accessibility best practices:
- Use
label
elements withfor
attributes. - Group related controls with
<fieldset>
and<legend>
. - Ensure visible focus indicators.
- Use
Section AO – Masking & Clipping
Note: Use clip-path
and mask
to show only portions of elements, apply decorative cutouts, or reveal content selectively. Both support basic shapes, paths, and gradients.
- AO.1 – Basic clip-path with a polygon:
.hex { clip-path: polygon(25% 6%, 75% 6%, 100% 50%, 75% 94%, 25% 94%, 0% 50%); }
Clips the element into a hexagon. Accepts `circle()`, `ellipse()`, `inset()` and more.
- AO.2 – Predefined shape clip examples:
.circle { clip-path: circle(50% at center); }
- AO.3 – Image masks with gradients:
.fade-mask { mask-image: linear-gradient(to bottom, black, transparent); -webkit-mask-image: linear-gradient(to bottom, black, transparent); }
Gradually hides bottom of element/image using a mask layer.
- AO.4 – External SVG masking:
Define a mask in SVG, then reference it with
mask
in CSS:.svg-mask { mask: url(#my-mask); mask-mode: alpha; }
- AO.5 – Combining with background-image:
.shape { background-image: url(bg.jpg); clip-path: circle(40%); }
- AO.6 – When to use:
- Custom-shaped buttons, cards, or avatars
- Image reveal or fade effects
- Component styling without extra SVG or JS
- AO.7 – Performance and support tips:
- Prefer
clip-path
for performance; it’s GPU accelerated - Add
-webkit-
prefix for better Safari support - Test across devices — masks have varying support depth
- Prefer
Section AP – CSS-Only UI Components
Note: With creative use of selectors like :checked
, :focus-within
, and :target
, you can build functional UI components entirely in CSS. These are ideal for minimal environments or performance-critical apps.
- AP.1 – Accordion using checkboxes:
<input type="checkbox" id="accordion1"> <label for="accordion1">Section Title</label> <div class="accordion-content">Content here...</div>
.accordion-content { max-height: 0; overflow: hidden; transition: max-height 0.3s ease; } input:checked + label + .accordion-content { max-height: 200px; }
- AP.2 – Tab interface with radio buttons:
<input type="radio" name="tabs" id="tab1" checked> <label for="tab1">Tab 1</label> <div class="tab-content">Content 1</div>
#tab1:checked ~ .tab-content-1 { display: block; }
- AP.3 – Modal using
:target
:<a href="#modal">Open Modal</a> <div id="modal" class="modal"> <a href="#" class="close">X</a> <p>Modal content here.</p> </div>
.modal { display: none; } #modal:target { display: block; }
- AP.4 – Tooltip using
:hover
:.tooltip { position: relative; } .tooltip::after { content: attr(data-tip); position: absolute; background: #000; color: white; padding: 4px 8px; top: 100%; left: 0; display: none; } .tooltip:hover::after { display: block; }
- AP.5 – When to use CSS-only UI:
- For simple components where full JS isn't needed
- In environments where JS is restricted
- For fast-loading, zero-dependency static pages
- AP.6 – Limitations:
- State doesn't persist beyond interaction
- No async data fetching or complex logic
- Accessibility must be handled manually
Section AQ – Layered Animations
Note: Layered animations coordinate multiple CSS effects using animation
, @keyframes
, transition-delay
, and stacking logic. These techniques produce complex motion sequences without JavaScript.
- AQ.1 – Basic animation stack:
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .element { animation: fadeIn 1s ease-in-out forwards; }
This fades in an element once it’s visible.
- AQ.2 – Sequential delay chaining:
.item:nth-child(1) { animation-delay: 0s; } .item:nth-child(2) { animation-delay: 0.2s; } .item:nth-child(3) { animation-delay: 0.4s; }
Triggers cascading animations in order.
- AQ.3 – Overlapping animation sequences:
@keyframes slideAndFade { 0% { transform: translateY(10px); opacity: 0; } 50% { transform: translateY(0); opacity: 1; } 100% { transform: translateY(-5px); } } .layered { animation: slideAndFade 1s ease-in-out forwards; }
- AQ.4 – Using multiple animations:
.multi { animation: fadeIn 0.5s ease-out, scaleUp 1s ease-in 0.5s; }
Multiple named animations can be layered with independent timing.
- AQ.5 – Staggered list reveal (example):
.list-item { animation: fadeIn 0.6s ease both; } .list-item:nth-child(n) { animation-delay: calc(0.1s * var(--i)); }
Works with CSS variables to create scalable staggered effects.
- AQ.6 – Scroll-triggered (using
:has
or:target
):section:target .reveal { animation: fadeIn 1s ease forwards; }
Use structural triggers to launch animations on interaction.
- AQ.7 – Best practices:
- Use
forwards
to retain end state - Combine
transition
+animation
for fine control - Use
will-change
for performance optimizations
- Use
Section AR – Filter Effects
Note: CSS filters modify the appearance of content without changing layout. They are ideal for hover effects, modal backdrops, or stylized visuals in UI/UX.
- AR.1 – Applying basic filters:
.filtered { filter: blur(4px) brightness(0.8); }
Applies multiple filters simultaneously.
- AR.2 – Common filter functions:
blur(px)
– Softens the imagebrightness(%)
– Lightens/darkenscontrast(%)
– Increases sharpnessgrayscale(%)
– Converts to monochromesepia(%)
– Adds warm tone filtersaturate(%)
– Boosts color intensityhue-rotate(deg)
– Shifts color wheelinvert(%)
– Inverts colorsopacity(%)
– Controls transparencydrop-shadow()
– Adds shadow that follows shape
- AR.3 – Filter on hover:
.card:hover { filter: brightness(1.2) saturate(1.3); }
Enhances visual engagement on interaction.
- AR.4 – Using
backdrop-filter
:.glass { backdrop-filter: blur(10px) brightness(0.9); background-color: rgba(255, 255, 255, 0.2); }
Applies filter effects to content behind an element. Combine with transparency.
- AR.5 – Performance tip:
- Use sparingly on large or dynamic containers
- GPU-accelerated but can trigger repaints on updates
will-change: filter;
helps performance
- AR.6 – When to use:
- Image previews and thumbnails
- UI state feedback and hover effects
- Glassmorphism and modals
- Artistic adjustments without altering source media
Section AS – Blend Modes & Isolation
Note: mix-blend-mode
and background-blend-mode
define how an element or its background interacts with what's underneath. isolation
lets you prevent blending with unrelated layers.
- AS.1 – mix-blend-mode (element-to-element):
.text { mix-blend-mode: difference; }
Makes text invert colors based on what's beneath it.
- AS.2 – background-blend-mode (background layers):
.hero { background-image: linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.5)), url('image.jpg'); background-blend-mode: multiply; }
Blends a background image with an overlay color/gradient.
- AS.3 – Common blend mode values:
normal
– Default, no blendingmultiply
– Darkens underlying layersscreen
– Lightens overall resultoverlay
– Combines multiply + screendarken / lighten
– Chooses darker/lighter pixelsdifference / exclusion
– Inverts based on contrast
- AS.4 – Using isolation:
.container { isolation: isolate; }
Prevents child blend modes from affecting outside elements.
- AS.5 – Practical use cases:
- Text overlays with invert or multiply
- Hero banners with layered backgrounds
- Hover effects with blending on images
- Preventing unintended global blend effect leaks
- AS.6 – Accessibility tips:
- Ensure blended text remains readable
- Avoid important contrast-dependent info inside blend layers
Section AT – Backdrop & Glassmorphism
Note: backdrop-filter
applies effects to the background behind an element. Glassmorphism combines this with transparency and subtle borders for a frosted-glass look.
- AT.1 – Basic backdrop blur:
.frosted { backdrop-filter: blur(12px); background-color: rgba(255, 255, 255, 0.15); }
Creates a translucent panel that blurs background content.
- AT.2 – Full glassmorphism panel:
.glass { backdrop-filter: blur(16px) brightness(0.9); background-color: rgba(255, 255, 255, 0.2); border: 1px solid rgba(255, 255, 255, 0.3); box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1); border-radius: 1rem; }
Ideal for modals, cards, and overlay containers.
- AT.3 – Requirements for effect:
- Element must have a transparent background
- Parent/container must have content behind it
- Use
position
andz-index
to stack properly
- AT.4 – Cross-browser support:
- Use
-webkit-backdrop-filter
for Safari - Ensure fallback styling (e.g. semi-transparent background) for unsupported browsers
.glass { -webkit-backdrop-filter: blur(16px); }
- Use
- AT.5 – Accessibility considerations:
- Ensure sufficient contrast against blurred backgrounds
- Consider disabling for users who prefer reduced transparency
- AT.6 – Glass effect on interactive UIs:
- Use for nav bars, cards, overlays, modals, dialog boxes
- Combine with
hover
,focus-within
, and transitions for polished interactivity
Section AU – Advanced Compositing
Note: Compositing governs how layered elements mix visually. Mastering isolation, filters, masks, and stacking order enables clean, predictable, high-performance visuals.
- AU.1 – Compositing context with
isolation
:.group { isolation: isolate; }
Prevents blend modes or filters from leaking to sibling or parent elements.
- AU.2 – Controlling paint order with
z-index
:.layer { position: relative; z-index: 10; }
Ensures consistent layer stacking and depth control.
- AU.3 – Composite + blend interaction:
.blend-layer { mix-blend-mode: overlay; z-index: 2; isolation: isolate; }
Combine stacking and blending without interference.
- AU.4 – Using
contain
for performance:.widget { contain: layout paint style; }
Limits scope of rendering and improves performance by containing paint and layout.
- AU.5 – Layered animation with isolation:
.anim-group { isolation: isolate; will-change: transform, opacity; }
Prevents GPU animations from triggering full re-renders of unrelated content.
- AU.6 – GPU-friendly stacking:
- Use
transform: translateZ(0)
to promote element to GPU layer - Use
will-change
to pre-optimize rendering
.gpu-layer { transform: translateZ(0); will-change: opacity; }
- Use
- AU.7 – Compositing use cases:
- UI cards with hover blur or brightness
- Dashboard widgets with filters and depth
- Nested blend containers in charts/infographics
- Glassmorphism + layered background effects
Section AV – Writing Robust Utility Classes
Note: Utility-first CSS emphasizes composability, where small, atomic classes apply specific rules (e.g. .text-center
, .mt-4
, .bg-blue
). This reduces the need for verbose selectors and improves consistency.
- AV.1 – Structure of utility classes:
.text-center { text-align: center; } .mt-4 { margin-top: 1rem; } .bg-blue { background-color: #007BFF; } .rounded { border-radius: 0.5rem; }
Each class is responsible for one rule only.
- AV.2 – Utility naming conventions:
p-[side]-[amount]
– Paddingm-[side]-[amount]
– Margintext-[align/size/color]
– Typographybg-[color]
– Background colorflex / grid / block
– Display utilities
- AV.3 – Creating spacing scales:
.m-0 { margin: 0; } .m-1 { margin: 0.25rem; } .m-2 { margin: 0.5rem; } .m-4 { margin: 1rem; }
Define consistent spacing increments for layout control.
- AV.4 – Responsive utility variants:
@media (min-width: 768px) { .md\\:text-left { text-align: left; } }
Use breakpoint prefixes for responsive styling.
- AV.5 – Benefits of utility-first architecture:
- Minimal custom selectors = cleaner codebase
- Highly reusable — no style duplication
- Faster development with predictable naming
- Easier debugging (styles are in class names)
- AV.6 – Utility class best practices:
- Follow a consistent naming system
- Use BEM or token-style conventions if needed
- Group utilities in layered sections (layout, text, color, spacing, etc.)
- Document your scale system clearly
- AV.7 – Limitations:
- Long class attributes on elements
- Harder to override in deep component trees
- May conflict with design systems using semantic classes
Section AW – CSS-Only Interactivity
Note: You can build toggles, dropdowns, accordions, tabs, and lightboxes using only CSS selectors and states. No JavaScript needed when behavior relies on checkboxes, radio buttons, and URL targets.
- AW.1 – Toggle using checkbox:
<input type="checkbox" id="toggle"> <label for="toggle">Show Details</label> <div class="content">Hidden content</div> input:checked + label + .content { display: block; }
- AW.2 – Tabs using radio buttons:
<input type="radio" name="tabs" id="tab1" checked> <input type="radio" name="tabs" id="tab2"> <div class="tab" id="content1">Tab 1</div> <div class="tab" id="content2">Tab 2</div> #tab1:checked ~ #content1 { display: block; } #tab2:checked ~ #content2 { display: block; }
- AW.3 – Modal using
:target
:<a href="#popup">Open Modal</a> <div id="popup"> <a href="#">Close</a> <p>Modal content</p> </div> #popup:target { display: block; }
- AW.4 – Accordion with checkbox and transitions:
.accordion-content { max-height: 0; overflow: hidden; transition: max-height 0.3s ease; } input:checked + label + .accordion-content { max-height: 100px; }
- AW.5 – Interactive button using
:hover
and:focus
:button:hover, button:focus { background-color: var(--primary); transform: scale(1.05); }
- AW.6 – State selectors to know:
:hover
– Mouse-over:focus
– Keyboard or mouse focus:checked
– Input checkbox/radio selected:target
– Element targeted in URL:focus-within
– Any child element has focus
- AW.7 – Limitations:
- No persistent state beyond page interaction
- Not ideal for data-driven or async content
- Best suited for static or progressively-enhanced interfaces
Section AX – Custom Scrollbars
Note: CSS allows you to override the native scrollbar appearance in WebKit-based browsers and partially in Firefox. These are often used for dark mode support or UI branding. Use sparingly and test thoroughly.
- AX.1 – WebKit scrollbar styling:
/* Scrollbar track */ ::-webkit-scrollbar { width: 10px; height: 10px; } /* Scrollbar thumb */ ::-webkit-scrollbar-thumb { background: #888; border-radius: 10px; } /* Scrollbar track background */ ::-webkit-scrollbar-track { background: #f1f1f1; }
These selectors work in Chrome, Safari, and Edge (WebKit-based engines).
- AX.2 – Hover & active states:
::-webkit-scrollbar-thumb:hover { background: #555; }
- AX.3 – Firefox scrollbar styling (limited):
scrollbar-color: #888 #f1f1f1; scrollbar-width: thin;
Only affects color and width — no full theming.
- AX.4 – Scoped scrollable element:
.scroll-area { overflow-y: scroll; max-height: 300px; }
Apply custom scroll styles to a specific container only.
- AX.5 – Accessibility best practices:
- Ensure thumb contrast meets WCAG standards
- Don’t hide scrollbars completely — breaks usability
- Use
auto
oroverlay
scrollbars on touch devices cautiously
- AX.6 – Use cases:
- Admin panels, chat windows, code blocks
- Dark themes needing neutral scroll visuals
- UI components that scroll (tables, modals, dropdowns)
Section AY – Forced Colors & Media Features
Note: Use media queries like forced-colors
, prefers-color-scheme
, and prefers-reduced-motion
to respond to the user's system or browser settings. These improve usability, accessibility, and compliance.
- AY.1 – Detecting forced colors mode (Windows High Contrast):
@media (forced-colors: active) { * { background-color: Canvas; color: CanvasText; } }
Overrides your UI to work with high-contrast environments.
- AY.2 – Detecting dark/light color scheme:
@media (prefers-color-scheme: dark) { body { background-color: #111; color: #eee; } } @media (prefers-color-scheme: light) { body { background-color: #fff; color: #000; } }
Allows your site to auto-adjust to OS theme.
- AY.3 – Detecting reduced motion preference:
@media (prefers-reduced-motion: reduce) { * { animation: none !important; transition: none !important; } }
Respects users who prefer minimal motion for accessibility reasons.
- AY.4 – Other useful media features:
prefers-contrast
– Detect high or low contrast preferenceprefers-reduced-transparency
– Detect transparency sensitivityinverted-colors
– Detect color inversion (deprecated)hover
– Detects if a hover-capable pointer is availablepointer
– Detects the accuracy of input device (fine/coarse/none)
- AY.5 – Best practices:
- Always test in system-level high contrast or dark/light themes
- Use CSS variables to adapt dynamically
- Don’t disable system behavior — work with it
Section AZ – Feature Queries (@supports
)
Note: @supports
lets you apply styles only if the browser supports a given property-value pair. This is essential for fallbacks and modern enhancements (e.g. grid, gap, container queries).
- AZ.1 – Basic usage:
@supports (display: grid) { .layout { display: grid; gap: 1rem; } }
This ensures grid layout is only applied if supported.
- AZ.2 – Fallback technique:
.layout { display: flex; } @supports (display: grid) { .layout { display: grid; } }
Applies flex by default, grid only when available.
- AZ.3 – Combining multiple conditions:
@supports (display: grid) and (gap: 1rem) { .grid { display: grid; gap: 1rem; } }
You can chain with
and
,or
, andnot
. - AZ.4 – Negation logic:
@supports not (backdrop-filter: blur(10px)) { .glass { background-color: rgba(255,255,255,0.85); } }
Fallback for browsers that don't support
backdrop-filter
. - AZ.5 – Use cases:
- Safely use CSS Grid, clamp(), container queries, etc.
- Enhance modern browser experience without breaking legacy
- Control compatibility boundaries for critical UI
- AZ.6 – Feature query tips:
- Always test in fallback and modern browsers
- Avoid using
@supports
as a replacement for feature detection JS - Use with variables, layout systems, or UI enhancements
Section BA – Interactivity Without JavaScript
Note: CSS-only interaction patterns can replicate many common UI behaviors. Combine form elements, selectors, and pseudo-classes like :checked
and :target
to manage UI state without scripts.
- BA.1 – Checkbox toggle pattern:
<input type="checkbox" id="menu-toggle"> <label for="menu-toggle">Toggle Menu</label> <nav class="menu">Navigation Links</nav> #menu-toggle:checked ~ .menu { display: block; }
Used to create show/hide menus, sidebars, etc.
- BA.2 – Tabs with radio buttons:
<input type="radio" name="tabs" id="tab1" checked> <label for="tab1">Tab 1</label> <div class="tab-content">Tab 1 content</div> #tab1:checked ~ .tab-content { display: block; }
Each tab is tied to a radio button state.
- BA.3 – Modal using
:target
:<a href="#popup">Open Modal</a> <div id="popup"> <a href="#">Close</a> <p>Modal content</p> </div> #popup:target { display: block; }
Opening modals via anchor targeting and CSS visibility.
- BA.4 – Accordion via max-height transitions:
.accordion-content { max-height: 0; overflow: hidden; transition: max-height 0.3s ease; } input:checked + .accordion-content { max-height: 200px; }
Use this for FAQ lists and collapsible sections.
- BA.5 – Hover/focus-based reveal:
.reveal:hover .tooltip, .reveal:focus-within .tooltip { opacity: 1; visibility: visible; }
For tooltips and contextual info popups.
- BA.6 – Interactive features possible with CSS only:
- Dropdowns
- Sidebars and modals
- Tabbed interfaces
- Hover cards and menus
- Accordion components
- Off-canvas navigation
- BA.7 – Best practices:
- Ensure focusability for accessibility (e.g. use labels, buttons)
- Use semantic HTML structures
- Test mobile and screen reader behavior carefully
Section BB – CSS Naming Conventions
Note: Following clear and systematic naming conventions improves maintainability, especially in large or team-based CSS projects. Common strategies include BEM, OOCSS, SMACSS, and utility-based systems.
- BB.1 – BEM (Block–Element–Modifier):
.button { } .button__icon { } .button--primary { }
Block: standalone component (e.g.
button
)
Element: a child part of the block (e.g.button__icon
)
Modifier: a variation of the block (e.g.button--primary
) - BB.2 – OOCSS (Object-Oriented CSS):
Separate structure (layout) from skin (style):
.media { display: flex; } .media-img { margin-right: 1rem; } .media-body { flex: 1; }
- BB.3 – SMACSS (Scalable and Modular Architecture):
.layout-header
,.module-button
,.state-hidden
- Classifies rules by role: base, layout, module, state, theme
- BB.4 – Utility-first naming:
.text-center .m-2 .px-4 .bg-gray
Functional naming that describes exact effect (used in Tailwind CSS).
- BB.5 – Naming best practices:
- Use lowercase and hyphens:
.main-nav
,.footer-links
- Be semantic and descriptive:
.form-input
not.blue-box
- Avoid IDs for styling – use classes instead
- Prefix utility or state classes if needed:
.u-text-center
,.is-active
- Use lowercase and hyphens:
- BB.6 – Class name collision prevention:
- Namespace by component or section (e.g.
.nav-menu
) - Use scoped utilities (
.u-padding
) - Combine with CSS Modules or inline styles for isolation in component frameworks
- Namespace by component or section (e.g.
- BB.7 – Automated naming helpers (optional):
- Linting: Stylelint, Prettier
- Atomic CSS tools: Tailwind, Tachyons
- Scoped systems: CSS Modules, BEM naming generators
Section BC – State Machine Logic (CSS-Only)
Note: CSS-only state logic allows the UI to change behavior based on form input states. This technique simulates "machines" where user input defines the current visual/interactive state — all without scripting.
- BC.1 – Two-state toggle logic (ON/OFF):
<input type="checkbox" id="switch"> <label for="switch">Toggle</label> <div class="state-on">On State</div> #switch:checked ~ .state-on { display: block; }
Binary logic – visible only when ON.
- BC.2 – Multi-state control with radios:
<input type="radio" name="step" id="step1" checked> <input type="radio" name="step" id="step2"> <div class="step" id="s1">Step 1</div> <div class="step" id="s2">Step 2</div> #step1:checked ~ #s1 { display: block; } #step2:checked ~ #s2 { display: block; }
Simulates a finite state machine where each step is mutually exclusive.
- BC.3 – State transitions using animation triggers:
#toggle:checked ~ .panel { animation: slide-in 0.3s ease forwards; }
Apply transitions only in a given state.
- BC.4 – CSS-only tabs as state machine:
- Each tab is a radio “state”
- Only one content section visible at a time
- Labels serve as “actions”
- BC.5 – Wizard with next/previous state logic:
<input type="radio" name="wizard" id="step1" checked> <label for="step2">Next</label> <div id="content1">Step 1 Content</div> #step1:checked ~ #content1 { display: block; }
Uses form input structure to control UI logic flow.
- BC.6 – Limitations of CSS state machines:
- No memory or persistence across page loads
- No dynamic logic branching (only hardcoded states)
- Not suitable for forms requiring conditional validation
- BC.7 – Best use cases:
- Accordions, toggles, multi-step onboarding
- CSS-only tabbed navigation
- Interactive quizzes (with radio or checkbox control)
Section BD – GPU Performance & Containment
Note: GPU optimization minimizes layout thrashing and repaints by isolating animations and render operations. The contain
property and hardware acceleration techniques like transform: translateZ(0)
improve rendering and animation smoothness.
- BD.1 – Promote an element to GPU layer:
.gpu-box { transform: translateZ(0); will-change: transform, opacity; }
Forces the browser to use the GPU to handle rendering for the element.
- BD.2 – Use
contain
to scope layout/render/paint:.widget { contain: layout paint style; }
Restricts layout calculations to the element and its children.
- BD.3 – Isolation and stacking:
.card { isolation: isolate; z-index: 0; }
Prevents composite artifacts from sibling interactions (useful for blend modes).
- BD.4 – Animate with GPU-friendly properties:
transform
(scale, translate, rotate)opacity
Avoid: animating
width
,height
,left
,top
, which trigger layout recalculation. - BD.5 – High-performance animation example:
.box { transition: transform 0.3s ease-out; } .box:hover { transform: scale(1.1); }
- BD.6 – Containment types:
contain: layout;
– Prevent layout reflow outsidecontain: paint;
– Prevent repainting other elementscontain: size;
– Enforce size isolationcontain: content;
– Applies all except size
- BD.7 – Best practices:
- Use
will-change
only when needed — overuse hurts perf - Test performance with browser dev tools (Layers, FPS, Paint)
- Wrap animated layers in containers with
contain
andisolation
- Use
Section BE – Framework Compatibility Notes
Note: Frameworks ship with opinionated styles, variables, and class structures. Custom CSS must be scoped and structured carefully to avoid unexpected overrides or conflicts.
- BE.1 – Avoid class name collisions:
- Prefix your classes:
.custom-btn
instead of.btn
- Use BEM or namespacing:
.myapp-header__nav
- Frameworks often use global class names — check docs before reuse
- Prefix your classes:
- BE.2 – Respect framework specificity:
- Frameworks may use `!important` or high-specificity selectors
- Use `:where()` or `:is()` to reduce specificity where needed
- Avoid over-cascading — test overrides carefully
- BE.3 – Framework overrides and resets:
/* Remove Bootstrap's margin reset */ body { margin: revert; }
Use
revert
or scoped selectors to undo opinionated styles. - BE.4 – Utility frameworks (Tailwind, etc.):
- Tailwind uses utility-first atomic classes (e.g.
text-sm
,bg-blue-500
) - Use
@layer utilities
or@apply
to extend cleanly - Avoid redefining utility names — it will break tailwind builds
- Tailwind uses utility-first atomic classes (e.g.
- BE.5 – Component-based libraries (React, Vue, etc.):
- Prefer scoped styles via CSS Modules or
:scoped
in Vue - Pass classes as props:
<Button class="my-btn">
- Use shadow DOM or isolated styles in Web Components
- Prefer scoped styles via CSS Modules or
- BE.6 – CSS variable collision protection:
:root { --myapp-accent-color: #ff6347; }
Namespace all global variables with your project prefix.
- BE.7 – General tips for compatibility:
- Never overwrite framework source files
- Use a layered override approach (`@layer base`, `@layer utilities`, etc.)
- Document all overrides in a dedicated override.css or section
Section BF – Dark/Light Mode Switching
Note: CSS supports both automatic and manual dark/light mode theming. Use prefers-color-scheme
to detect system preference and toggle CSS variables or themes manually — all without JavaScript.
- BF.1 – Auto-detect system theme using media query:
@media (prefers-color-scheme: dark) { body { background-color: #111; color: #eee; } } @media (prefers-color-scheme: light) { body { background-color: #fff; color: #111; } }
This method automatically switches the theme based on the user's OS/browser settings.
- BF.2 – Manual theme control using CSS variables:
:root { --bg: #ffffff; --text: #111111; } [data-theme="dark"] { --bg: #111111; --text: #eeeeee; } body { background-color: var(--bg); color: var(--text); }
This setup allows switching the theme by changing the
data-theme
attribute in HTML. - BF.3 – Simulated dark/light toggle using checkbox (no JavaScript):
<input type="checkbox" id="theme-toggle" hidden> <label for="theme-toggle">Toggle Dark Mode</label> <div class="theme-wrapper"> <p>This content theme responds to toggle.</p> </div> <style> :root { --bg: #ffffff; --text: #111111; } #theme-toggle:checked ~ .theme-wrapper { --bg: #111111; --text: #eeeeee; } .theme-wrapper { background-color: var(--bg); color: var(--text); padding: 1rem; } </style>
This toggles between light and dark themes using a checkbox state and CSS variables only.
- BF.4 – Tips for dark mode design:
- Always validate contrast ratios (WCAG compliance)
- Apply theme consistently to UI elements (buttons, cards, nav)
- Use variables for maintainability
- BF.5 – Best practices:
- Avoid hardcoded dark/light colors in components
- Use smooth transitions:
transition: background-color 0.3s, color 0.3s;
- Test on real devices and different browsers
Section BG – Safe Area Insets (Mobile)
Note: On mobile browsers with dynamic display regions (e.g., iPhones with notches), environment variables help prevent content overlap with OS UI. Use env(safe-area-inset-*)
to dynamically pad UI.
- BG.1 – Common inset environment variables:
safe-area-inset-top
safe-area-inset-right
safe-area-inset-bottom
safe-area-inset-left
Values dynamically match the device’s display constraints.
- BG.2 – Apply padding with safe insets:
body { padding-top: env(safe-area-inset-top); padding-right: env(safe-area-inset-right); padding-bottom: env(safe-area-inset-bottom); padding-left: env(safe-area-inset-left); }
Prevents text, headers, and footers from being obscured.
- BG.3 – Set minimum fallback padding:
body { padding-top: max(20px, env(safe-area-inset-top)); }
Ensures usable padding on all devices.
- BG.4 – Scoped safe insets (e.g., navbar):
.navbar { padding-top: env(safe-area-inset-top); }
Target UI zones that need specific protection.
- BG.5 – Test behavior:
- View site in full-screen Safari or mobile emulator
- Rotate device to see dynamic inset changes
- Inspect values via DevTools → Computed tab
- BG.6 – Best practices:
- Use environment variables with
max()
orclamp()
for safety - Combine with media queries for specific mobile layouts
- Avoid hardcoded pixel values that assume flat viewports
- Use environment variables with
Section BH – CSS Hacks & Escape Techniques
Note: CSS hacks should be used sparingly and only when necessary, ideally with fallback strategies. Most hacks target legacy browsers, specificity collisions, or unsupported features.
- BH.1 – Targeting specific browsers (e.g., Internet Explorer):
/* Target IE 10+ */ @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) { .legacy-fix { margin-top: -1px; } }
Detects high-contrast mode in IE as a proxy for targeting IE10+.
- BH.2 – Safari-only hacks using @supports:
@supports (-webkit-hyphens: none) { .safari-only { padding-bottom: 2rem; } }
Targets WebKit-specific features that are only supported in Safari.
- BH.3 – Escape selector specificity (last resort):
.override { all: unset; }
all: unset
clears nearly all inherited and applied styles. - BH.4 – Use
!important
to force override:.btn { background: red !important; }
Forces the rule to take priority — avoid overusing this pattern.
- BH.5 – Using attribute selectors to escape bad IDs/classes:
[class^="js-"] { pointer-events: none; }
Useful for legacy code with unpredictable class naming.
- BH.6 – Using high-specificity selectors intentionally:
html body main section article .box { border: 1px solid red; }
Only use when lower-specificity selectors are being overridden.
- BH.7 – Target Firefox with specific @-moz support:
@-moz-document url-prefix() { .firefox-hack { font-weight: 600; } }
This only runs in Firefox. Deprecated but still functional in some versions.
- BH.8 – Combine vendor-prefixed properties:
.glassy { -webkit-backdrop-filter: blur(8px); backdrop-filter: blur(8px); }
Ensures broader compatibility for modern effects like glassmorphism.
- BH.9 – Fallback strategies:
- Use progressive enhancement: apply modern features only if supported
- Test on multiple browsers and OS combinations
- Document hacks inline with comments (with date, reason, and affected browser)
Section BI – Accessibility & Reduced Motion Handling
Note: CSS can help make your UI more inclusive by supporting reduced motion, visible focus states, high contrast, and semantic structure. Always test for screen reader and keyboard navigation support.
- BI.1 – Respect user’s reduced motion preference:
@media (prefers-reduced-motion: reduce) { * { animation: none !important; transition: none !important; scroll-behavior: auto !important; } }
Disables transitions and animations when the user has requested minimal motion.
- BI.2 – Ensure visible focus indicators:
button:focus, a:focus { outline: 2px solid #00f; outline-offset: 2px; }
Always retain visible outlines to help keyboard users navigate.
- BI.3 – Use system fonts for legibility and screen reader compatibility:
body { font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
Improves readability and respects OS-level font adjustments.
- BI.4 – High contrast support (with forced colors):
@media (forced-colors: active) { .card { border: 1px solid ButtonText; background: Canvas; color: CanvasText; } }
Supports accessibility tools like Windows High Contrast mode.
- BI.5 – Avoid using only color to convey meaning:
Pair color cues with icons or text for users with color vision deficiency.
- BI.6 – Avoid animations that flash, flicker, or disorient:
- No rapid flashing over 3 times/second
- No sudden zoom, spin, or shake effects
- Respect vestibular disorders by avoiding parallax or auto-play loops
- BI.7 – Screen reader-safe content hiding:
.visually-hidden { position: absolute; width: 1px; height: 1px; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }
Makes content invisible visually but still readable by assistive tech.
Section BJ – Print & Pagination Features (@page
)
Note: Use print-specific styles and the @page
at-rule to optimize documents for printing. Print CSS helps eliminate unnecessary elements, format content, and handle page breaks.
- BJ.1 – Basic print media query:
@media print { body { font-size: 12pt; color: black; background: white; } }
Wrap styles in
@media print
to apply them only when printing. - BJ.2 – Remove unnecessary UI from print:
@media print { nav, footer, .no-print { display: none !important; } }
Use a class like
.no-print
to flag elements to hide in print view. - BJ.3 – Add page break rules:
.page-break { page-break-before: always; }
Forces a new page before the element when printed.
- BJ.4 – Define printed page size and margins:
@page { size: A4; margin: 1in; }
Controls paper size and page layout (use
letter
,A4
,landscape
, etc.). - BJ.5 – Print header/footer control (limited support):
@page { @top-left { content: "My Document"; } @bottom-right { content: counter(page); } }
Experimental in most browsers—some support in paged media generators like PrinceXML or PDF output engines.
- BJ.6 – Optional: Print-only styles:
.print-only { display: none; } @media print { .print-only { display: block; } }
Show additional content only in printed versions (e.g., disclaimers, citations).
Section BK – Experimental & Deprecated Features
Note: Use experimental features with caution and behind feature detection. Avoid deprecated properties in production unless absolutely necessary for legacy support.
- BK.1 – Experimental (use with
@supports
):anchor-position
(CSS Anchor Positioning)subgrid
(Extended CSS Grid layout, partial Firefox/Chrome support)scroll-timeline
/@scroll-timeline
(CSS Scroll-Linked Animations)container-type: inline-size
(part of Container Queries)has()
selector (e.g.,:has(img)
) – supported in modern Chrome, Safari
- BK.2 – Deprecated or Obsolete:
<font>
tag – HTML-level font styling is obsoletezoom
– non-standard (works in IE/Chrome only, avoid)clip
(useclip-path
instead)-webkit-marquee
– deprecated, experimental WebKit-only featurefloat
for layout – replaced by Flexbox and Grid
- BK.3 – Experimental pseudo-elements:
::view-transition, ::spelling-error, ::grammar-error
These may be browser-specific or experimental and should be avoided unless controlled.
- BK.4 – Avoid over-reliance on browser prefixes:
/* Bad: */ -webkit-transform: rotate(45deg); -moz-transform: rotate(45deg); transform: rotate(45deg);
Only use prefixes when absolutely needed. Use tools like Autoprefixer instead.
- BK.5 – Best practices:
- Always wrap new features with
@supports
for fallback:
@supports (scroll-timeline: auto) { .anim { scroll-timeline: customTimeline; } }
- Always wrap new features with
- Check compatibility on CanIUse.com before use
- Avoid deprecated syntax in modern projects
Section BL – Unit Reference Table
Note: Always choose units based on context — use relative units (like em
, rem
, %
) for fluid layouts, and viewport units (vw
, vh
) for responsive scaling.
Unit | Type | Description | Common Use |
---|---|---|---|
px |
Absolute | Pixel — fixed size on screen, not scalable | Fine control of borders, spacing, layout |
em |
Relative | Relative to the font-size of the parent | Font sizing, spacing, nested elements |
rem |
Relative | Relative to the root html font-size |
Consistent sizing across entire document |
% |
Relative | Percentage of containing block | Fluid width/height, responsive layout |
vw |
Viewport | 1% of the viewport width | Hero sections, responsive typography |
vh |
Viewport | 1% of the viewport height | Full-screen layouts, vertical centering |
vmin |
Viewport | Smaller of vw and vh |
Scale elements based on smaller dimension |
vmax |
Viewport | Larger of vw and vh |
Responsive UI with maximum expansion |
ch |
Relative | Width of the "0" character in current font | Text boxes, monospace control |
ex |
Relative | Height of the lowercase "x" | Font-based vertical sizing |
lh |
Relative | Line-height unit, relative to the element’s line-height |
Typography control, spacing |
fr |
Grid-specific | Fractional unit for CSS Grid layout | Distribute space in grid columns/rows |
cm / mm / in |
Absolute | Physical dimensions — rarely used | Print CSS or exact physical layouts |
pt / pc |
Absolute | Point and pica — for print typography | Legacy typesetting or PDFs |
Best practices:
- Use
rem
for global consistency - Use
em
for localized scaling (e.g., padding in buttons) - Use
%
andvw/vh
for fluid responsiveness - Avoid
px
for font sizing in responsive design - Use
fr
only in CSS Grid context
Section BM – Snippet Library
Note: These CSS-only code snippets provide quick solutions for layout, utility classes, helpers, and responsive design — all usable without JavaScript.
- BM.1 – Center anything (absolute):
.center-abs { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
Perfect for centering modals, loaders, etc.
- BM.2 – Responsive square:
.square { aspect-ratio: 1 / 1; width: 100%; }
Maintains a 1:1 ratio at any screen size.
- BM.3 – Clearfix utility:
.clearfix::after { content: ""; display: table; clear: both; }
Clears floated elements inside containers.
- BM.4 – Responsive image class:
.img-fluid { max-width: 100%; height: auto; display: block; }
Prevents images from overflowing containers.
- BM.5 – Visually hidden (but accessible):
.visually-hidden { position: absolute; width: 1px; height: 1px; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
Hides content from view but keeps it screen-reader accessible.
- BM.6 – Aspect ratio utility (16:9):
.aspect-16-9 { aspect-ratio: 16 / 9; }
Ensures elements like videos maintain their ratio.
- BM.7 – Truncate text with ellipsis:
.truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
Single-line text truncation for cards or tables.
- BM.8 – Responsive container max-width:
.container { width: 100%; max-width: 1280px; margin-inline: auto; padding-inline: 1rem; }
Consistent layout wrapper for all screens.
- BM.9 – Custom scrollbar styling (WebKit only):
::-webkit-scrollbar { width: 10px; } ::-webkit-scrollbar-track { background: #f1f1f1; } ::-webkit-scrollbar-thumb { background: #888; } ::-webkit-scrollbar-thumb:hover { background: #555; }
Customize scrollbars for a better UI experience (Chrome/Safari).
Section BN – CSS Functions Index
Note: CSS functions allow for dynamic styling, filtering, responsive math, and logic-based property control. Most are usable in any modern browser.
Function | Purpose | Example |
---|---|---|
calc() |
Performs math in CSS | width: calc(100% - 2rem); |
min() |
Returns the smallest value | width: min(400px, 100%); |
max() |
Returns the largest value | height: max(2rem, 10vh); |
clamp() |
Constrains a value within a range | font-size: clamp(1rem, 2vw, 2rem); |
var() |
Access a CSS custom property | color: var(--primary); |
url() |
References external assets | background: url("image.jpg"); |
rgba() , hsla() |
Define colors with transparency | color: rgba(0, 0, 0, 0.5); |
attr() |
Access HTML attributes in content | content: attr(data-label); |
env() |
Access device environment values | padding: env(safe-area-inset-top); |
round() (future) |
Rounding math — limited support | margin: round(33.33%, 5%); |
color-mix() |
Mixes two colors | color: color-mix(in srgb, red 50%, blue); |
image-set() |
Responsive image loading | background-image: image-set("low.jpg" 1x, "high.jpg" 2x); |
linear-gradient() |
Creates gradients | background: linear-gradient(to right, #000, #fff); |
Best practices:
- Use
clamp()
for responsive typography and spacing - Use
calc()
when you need dynamic layout math - Wrap all fallback-unsafe functions with
@supports
when needed - Use
var()
+calc()
for modular scale systems
Section BO – Visual Debug Patterns
Note: Use debug patterns to visualize box model behavior, stacking context, z-index issues, or layout anomalies. These should be removed or toggled off before deployment.
- BO.1 – Outline all elements:
* { outline: 1px solid red; }
Draws borders around every element — ideal for visualizing structure.
- BO.2 – Debug class with dashed border:
.debug { border: 2px dashed hotpink !important; background: rgba(255, 0, 255, 0.05); }
Apply to individual components when troubleshooting alignment.
- BO.3 – Show z-index stacking with colored overlays:
.z-index-map * { outline: 1px solid rgba(0, 0, 0, 0.2); background-blend-mode: multiply; }
Apply to a region where overlapping is breaking stacking behavior.
- BO.4 – Add box model visualization:
.box-debug { padding: 1rem; border: 2px dashed #09f; margin: 1rem; background-color: rgba(0, 128, 255, 0.1); }
Helps detect padding vs. margin overflow.
- BO.5 – Visualize empty elements:
*:empty { background: rgba(255, 0, 0, 0.2); }
Highlights accidentally empty containers that break layout.
- BO.6 – Detect off-screen content:
* { outline: 1px dotted green; transform: translateZ(0); }
Triggers GPU compositing to help debug reflow or position issues.
- BO.7 – Print layout testing (optional):
@media print { * { outline: 1px dashed gray; } }
Force box outlines in printed output to test page breaks.
Section BP – Cross-Browser Compatibility Practices
Note: Different browsers render styles with subtle (or major) differences. Use these practices to minimize issues and ensure a consistent UI.
- BP.1 – Normalize/reset default styles:
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
Prevents inconsistencies in box sizing, spacing, and element behavior.
- BP.2 – Use feature detection (
@supports
):@supports (aspect-ratio: 1) { .box { aspect-ratio: 1 / 1; } }
Only applies code when supported by the browser — avoids silent failures.
- BP.3 – Avoid using deprecated or vendor-specific properties:
/* ❌ Bad: */ -webkit-box-shadow, -moz-box-shadow /* ✅ Use: */ box-shadow
Use standards-based properties. Let build tools handle prefixing.
- BP.4 – Use CSS variables for fallback flexibility:
:root { --accent: #0af; } .element { background: var(--accent, blue); }
Provides browser-safe fallback values with
var()
. - BP.5 – Beware of browser quirks:
- Safari has issues with flex gaps (pre-v14)
- Firefox handles
min-content
differently in some contexts - iOS Safari has unique safe-area insets
- BP.6 – Use logical properties for direction-aware layout:
padding-inline: 1rem; margin-block: 2rem;
Improves support for RTL (right-to-left) languages and better future-proofing.
- BP.7 – Test with a cross-browser matrix:
- Chrome (desktop/mobile)
- Firefox
- Safari (macOS and iOS)
- Edge
- Samsung Internet / Android
Test on real devices or simulators if possible.
- BP.8 – Validate CSS and check support:
- Can I Use – Feature support reference
- W3C CSS Validator
- Use
DevTools
console warnings and experiment tabs
Section BQ – Layered Responsive Design Patterns
Note: These patterns leverage multiple CSS technologies layered together for resilient, responsive, and scalable UIs.
- BQ.1 – Mobile-first base + media query scaling:
.box { padding: 1rem; } @media (min-width: 768px) { .box { padding: 2rem; } }
Start with a mobile baseline, then scale up as the screen grows.
- BQ.2 – Container queries for local responsiveness:
@container (min-width: 400px) { .card { display: flex; } }
Responsive layout behavior based on the component’s container size — not the viewport.
- BQ.3 – Fluid typography via
clamp()
:h1 { font-size: clamp(1.5rem, 2.5vw, 3rem); }
Scales smoothly across all screen sizes with min/max safety bounds.
- BQ.4 – Logical properties for direction-aware layouts:
.content { padding-inline: 1rem; margin-block: 2rem; }
Support both LTR and RTL languages naturally.
- BQ.5 – Responsive utility classes (mobile-first):
.hide-mobile { display: none; } @media (min-width: 640px) { .hide-mobile { display: block; } }
Enable component-level visibility control across breakpoints.
- BQ.6 – Progressive enhancement layers with
@layer
:@layer reset, base, components, utilities;
Organize CSS logic and override sequence without specificity battles.
- BQ.7 – Combine viewport + container + logical + flex/grid:
.layout { display: grid; grid-template-columns: 1fr; gap: 1rem; padding-inline: clamp(1rem, 5vw, 3rem); } @container (min-width: 600px) { .layout { grid-template-columns: repeat(2, 1fr); } }
Example of fully layered responsive technique across multiple modern features.
Best Practices:
- Design mobile-first, scale up with media + container queries
- Use
clamp()
,min()
, andmax()
for fluid size control - Modularize styles into layers: reset → base → components → utilities
- Use logical properties for internationalization and layout resilience
Section BR – Color Accessibility & Contrast Optimization
Note: Use high contrast and semantic colors to ensure readability for all users. WCAG guidelines recommend a contrast ratio of at least 4.5:1 for normal text.
- BR.1 – Use accessible color pairs:
.text-light-on-dark { color: #ffffff; background-color: #000000; } .text-dark-on-light { color: #000000; background-color: #ffffff; }
Simple example of strong contrast in light and dark themes.
- BR.2 – Define contrast-safe variables:
:root { --bg: #ffffff; --text: #111111; --link: #0033cc; } [data-theme="dark"] { --bg: #000000; --text: #eeeeee; --link: #66ccff; } body { background: var(--bg); color: var(--text); }
Ensure colors switch modes while maintaining legibility.
- BR.3 – Underline links for color-blind users:
a { color: var(--link); text-decoration: underline; }
Do not rely on color alone to indicate interactivity.
- BR.4 – Avoid red/green combinations:
.status-success { color: #1a7f37; /* Green */ } .status-error { color: #d32f2f; /* Red */ } .status-text { font-weight: bold; text-decoration: underline dotted; }
Use both color and additional cues (text/icons/decoration).
- BR.5 – WCAG contrast ratios (reference):
- Normal text: 4.5:1
- Large text (18pt+): 3:1
- UI components (borders/icons): 3:1
- BR.6 – Tools to test contrast:
- WebAIM Contrast Checker
- Contrast-Ratio.com
- Browser DevTools → Accessibility → Contrast
Best Practices:
- Use semantic color naming (e.g.,
--primary
,--danger
) - Always pair color changes with text/icon changes
- Use media queries to adapt themes (
prefers-color-scheme
) - Test every color pair with contrast tools
Section BS – Browser Engine Quirks
Note: Even with standards-based CSS, different engines have quirks. Knowing them prevents bugs and improves stability across platforms.
- BS.1 – Safari ignores flexbox gap (pre-v14):
/* Fix: Use margin fallback */ .flex-row > * + * { margin-left: 1rem; }
Early Safari versions didn’t support
gap
in flex containers. - BS.2 – iOS Safari double-tap zoom issues:
html { touch-action: manipulation; }
Prevents unintentional zooming on interactive elements like buttons.
- BS.3 – Firefox table-cell padding inconsistencies:
Test padding inside
<td>
on Firefox — it may render slightly taller rows than Chrome. - BS.4 – Edge/Chrome subpixel rounding differences:
Layout gaps or blurry edges can occur due to subpixel math. Use
transform: translateZ(0)
to trigger GPU smoothing if needed. - BS.5 – Android WebView font rendering:
* { -webkit-font-smoothing: antialiased; }
Improves legibility on lower-end devices running WebView apps.
- BS.6 – Safari overflow hidden bug:
.parent { position: relative; overflow: hidden; } .child { position: absolute; }
Safari may clip positioned children incorrectly unless containment context is established.
- BS.7 – Mobile address bar jump:
Use
100dvh
instead of100vh
in modern CSS to prevent layout jump from hiding the URL bar on scroll.
Best Practices:
- Test frequently in Safari, Firefox, Chrome, and Edge
- Use
@supports
for experimental or flaky features - Refer to browser bug trackers for long-standing issues
- Minimize hardcoded heights to reduce layout variance
Section BT – Production Deployment and Minification
Note: Production-ready CSS must be compact, fast-loading, and clean. This step involves optimizing output for browsers while preserving visual fidelity and responsive behavior.
- BT.1 – Minify your CSS:
/* From this: */ body { background: #fff; color: #111; } /* To this: */ body{background:#fff;color:#111}
Use tools like CSS Minifier or CLI tools like
csso
orpostcss
plugins. - BT.2 – Remove unused CSS:
/* Tools: */ - PurgeCSS - UnCSS - Tailwind CSS safelist config
Strip out dead styles not used in your HTML to reduce file size.
- BT.3 – Use media queries and container queries sparingly:
Overuse can bloat stylesheets and confuse override logic. Keep breakpoints clean and purposeful.
- BT.4 – Audit CSS file size and performance:
Use Lighthouse, Chrome DevTools → Coverage tab, or WebPageTest to detect unused or inefficient CSS delivery.
- BT.5 – Use a content delivery network (CDN):
If serving static files, host the CSS on a CDN (e.g., Cloudflare, Netlify) for faster access worldwide.
- BT.6 – Set proper caching headers:
Use long-term caching headers for `style.css`, then version the filename to force updates (e.g., `style.v2.css`).
- BT.7 – Validate final CSS:
- Use W3C CSS Validator
- Ensure your custom properties and selectors have full support
- BT.8 – Optional: Inline critical CSS:
<style> /* above-the-fold styles */ </style>
Improves perceived speed by rendering the top of the page before the full CSS loads.
Best Practices:
- Keep CSS modular and layered (use
@layer
or import order) - Document styles or include a changelog
- Back up both unminified and minified versions
- Validate, test, compress, and deploy via version control