CSS3 Cheatsheet - CSS3 Properties & Layout Reference

Most CSS pain is not about forgetting property names. It is about not knowing which declaration won the cascade, why a computed width disagrees with the design file, and whether a layout problem belongs to Flexbox or Grid. So this sheet starts with selector specificity and the box model, including border-box and margin collapsing, then draws a firm line between the two layout systems: one axis means Flex, simultaneous row and column control means Grid, and anything out of normal flow means positioning. Visual and motion sections cover gradients, shadows, transitions and keyframes before the responsive breakpoints land at the end. What matters more than any single rule is the reasoning behind the choice, for example knowing that justify-content works on the main axis while align-items works on the cross axis, and reaching for fr and minmax rather than hard-coded percentages when sizing Grid tracks. Custom properties extend the same logic to runtime theming, so a colour or spacing decision can live in one token rather than being repeated per selector.

Web Services·47 commands·Last updated 2026-07-21

Typical Use Case

For web developers writing styles by hand or working without a framework. Eight lines organise the sheet: selectors, the box model, Flex, Grid, positioning, backgrounds and gradients, animation, and responsive design. Three items deserve priority — border-box so width includes padding and border, Flex for one dimension against Grid for two, and mobile-first media queries using min-width to grow toward larger screens. When a layout misbehaves — an element that will not centre, absolute positioning pinned to the top-left, flex children that refuse to wrap — the cause is almost always in those three. Use clamp for fluid type, rem for spacing, and transform for motion.

Selectors 8

.class
Class selector
#id
ID selector
div p
Descendant selector
div > p
Child selector
a:hover
Hover pseudo-class
::before / ::after
Pseudo-elements
[type="text"]
Attribute selector
nth-child(2n)
Even-child selector

Box Model 6

width / height
Content box size
padding
Inner spacing
border
Border
margin
Outer spacing
box-sizing: border-box
Include border & padding in size
border-radius
Rounded corners

Layout 8

display: block
Block-level box
display: inline-block
Inline but sizeable
display: flex
Flex container
display: grid
Grid container
display: none
Hide element (no box)
position: relative / absolute / fixed
Positioning context
float: left / right
Float
z-index
Stacking order

Colors & Background 7

color
Text color
background
Background shorthand
background-image: url()
Background image
background-size: cover
Cover container
opacity
Element transparency
box-shadow
Drop shadow
linear-gradient()
Gradient background

Text 6

font-size
Font size
font-weight
Font weight
text-align
Horizontal alignment
line-height
Line spacing
letter-spacing
Character spacing
white-space: nowrap
No wrapping

Transitions & Animations 6

transition: all 0.3s
Smooth transition
transform: translateX(10px)
Translate
transform: scale(1.2)
Scale
transform: rotate(45deg)
Rotate
@keyframes name { 0% {} 100% {} }
Define animation
animation: name 1s infinite
Apply animation

Responsive 6

@media (max-width: 768px) { }
Media query
max-width: 100%
Max width
min-width: 0
Min width
vw / vh / vmin / vmax
Viewport units
rem / em
Relative units
clamp(1rem, 2vw, 2rem)
Responsive value clamp

Parameter matrix

ParameterEffectExample
.class / #id / elementInclude padding and border in the declared width and height, which makes size math predictable..card { padding: 10px; }
parent > childMatch only the direct children, so a deeply nested paragraph is not affected by the rule.nav > ul { margin: 0; }
ancestor descendantSelect by attribute value, which is the only reliable way to target an input type in HTML.div p { color: #333; }
element + sibling / element ~ siblingSelect elements by their position among siblings, with 2n for every second one.h2 + p { margin-top: 0; }
[attr] / [attr="value"]Pin an element once the scroll passes a threshold while it still occupies space in flow.input[type="text"] { width: 100%; }
:hover / :focus / :activeTurn the element into a flex or grid container, which changes how its children are laid out.a:hover { color: blue; }
::before / ::afterMove, scale or rotate an element with a composited transform that does not trigger layout.p::before { content: "· "; }
width / heightScale a value fluidly between a minimum and a maximum, replacing most media queries for type.width: 100px; height: 100px;
margin / paddingApply rules only when the viewport is at or below a width, which is the desktop-first override.margin: 10px; padding: 10px;
borderTell the browser a property is about to animate so it promotes the element to its own layer.border: 1px solid #000;
box-sizing: border-boxOrder siblings inside the same stacking context; a high value on a child of a positioned parent has no effect outside it.* { box-sizing: border-box; }
display: block / inline / inline-blockScale a background image until it covers the box, cropping the overflow rather than distorting it..btn { display: inline-block; }
display: none移除元素,不占位.hidden { display: none; }
visibility: hidden不可见但仍占布局空间.mask { visibility: hidden; }
opacity: 0.5整体透明度(含内容).faded { opacity: 0.5; }
display: flex启用 Flex 布局.row { display: flex; }
flex-direction: row / column主轴方向flex-direction: column;
justify-content主轴对齐:flex-start / center / space-betweenjustify-content: center;
align-items交叉轴对齐:stretch / center / flex-startalign-items: center;
flex: 1弹性增长并占满剩余空间.grow { flex: 1; }
flex-wrap: wrap空间不足时换行flex-wrap: wrap;
gap: 10px元素间距gap: 10px;
display: grid启用 Grid 布局.grid { display: grid; }
grid-template-columns定义列轨道grid-template-columns: 1fr 1fr 1fr;
grid-template-rows定义行轨道grid-template-rows: 100px auto;
grid-gap: 10px网格行列间距grid-gap: 10px;
grid-column: 1 / 3元素跨列grid-column: 1 / 3;
grid-row: 1 / 3元素跨行grid-row: 1 / 3;
grid-template-areas命名区域排版grid-template-areas: "header" "main" "footer";
position: relative相对自身定位,作为 absolute 的参照.wrap { position: relative; }
position: absolute相对最近定位祖先定位.badge { position: absolute; }
position: fixed相对视口固定,不随滚动移动.bar { position: fixed; }
position: sticky滚动到阈值后固定.nav { position: sticky; }
top/right/bottom/left定位偏移量top: 0; left: 0;
z-index: 100层叠顺序z-index: 100;
background-image: url()背景图background-image: url("bg.jpg");
background-size: cover / contain背景图铺满 / 完整显示background-size: cover;
linear-gradient()线性渐变linear-gradient(to right, #000, #fff);
radial-gradient()径向渐变radial-gradient(circle, #000, #fff);
transition: all 0.3s ease属性变化过渡动画transition: all 0.3s ease;
transform: translateX / scale / rotate位移 / 缩放 / 旋转(不触发重排)transform: scale(1.5);
@keyframes / animation定义关键帧并循环应用animation: name 1s infinite;
@media (max-width: 768px)媒体查询断点@media (max-width: 768px) { .nav { display: none; } }
vw / vh / vmin / vmax视口单位:宽 / 高 / 最短边 / 最长边width: 100vw;
rem / em相对根元素 / 父元素字号的单位font-size: 1.25rem;
clamp(min, preferred, max)响应式取值,在区间内随视口缩放font-size: clamp(1rem, 2vw, 2rem);

Common pitfalls

SymptomA child overflows its parent and the parent does not grow to contain it.

CauseA grid or flex item defaults to min-width: auto, so its content refuses to shrink below its intrinsic width.

FixSet min-width: 0 (or min-height: 0) on the item so it can actually shrink inside the track.

SymptomAnimating an element causes the whole page to jump or text to flicker during the transition.

CauseThe animated property is width, height, top or left, all of which force layout and repaint on every frame.

FixAnimate transform and opacity instead, which run on the compositor, or switch the layout to flex/grid and animate flex-grow or grid-template-columns.

SymptomA z-index of 9999 does not bring a tooltip above an overlay.

CauseThe tooltip and the overlay live in different stacking contexts because their common ancestor creates one with opacity, transform or filter.

FixRender both in the same stacking context, or move the tooltip to the top level with position: fixed and a high z-index where nothing creates a new context.

SymptomA margin declared on the last flex item or the last grid item is ignored.

CauseIn flex and grid layout, margins do not collapse; the gap property is what separates tracks, and trailing margins do add to the container size.

FixUse row-gap / column-gap or padding on the container instead of relying on margin collapse, which only happens in normal block flow.

Symptomposition: sticky has no effect on a table cell or a container with overflow: hidden on an ancestor.

CauseThe nearest scrolling ancestor is not the element itself, or the sticky element has a fully clipped overflow ancestor, so it never reaches its threshold.

FixRemove overflow: hidden from the scroll container and apply sticky to the direct child of the scrolling box, or move the scroll onto the intended element.

SymptomTwo media queries for the same breakpoint both match, or neither matches on a tablet.

CauseMixing desktop-first max-width queries with mobile-first min-width queries makes the cascade depend on source order rather than intent.

FixPick one strategy for the project and check the boundaries at exactly 768px, since max-width: 768px includes 768 while min-width: 769px excludes it.

SymptomA high-resolution image looks blurry on a retina display even though it is large in CSS pixels.

CauseThe image is sized to half the device pixels (for example 100x100 CSS px on a 2x screen) with no srcset to supply a larger asset.

FixShip a 2x asset via srcset and sizes, or use an image CDN that generates the variants.

Symptom父容器设置了 flex-wrap: wrap,子项仍被挤成一行且内容溢出

Causeflex 子项的 min-width 默认是 auto,内容最小宽度可能超过换行判断,导致宁可溢出也不换行。

Fix给需要收缩的子项设置 min-width: 0(同时配合 overflow 处理),让换行判定基于真正可用宽度。

Troubleshooting

  1. 1Check which rule actually won the cascade

    * { box-sizing: border-box; }

    In DevTools, selecting an element and reading its computed style shows the resolved value and the rules that contributed to it.

  2. 2Measure the box to see where the space goes

    display: flex; justify-content: space-between; align-items: center; gap: 10px;

    The returned width and height are the border box, so it shows directly whether padding and border are being added on top of width.

  3. 3Find out which properties force layout when animated

    display: grid; grid-template-columns: 1fr 1fr 1fr; grid-gap: 10px;

    Listing the animated keyframes tells you whether you are animating a layout-triggering property.

  4. 4Audit colour contrast against WCAG AA

    .wrap { position: relative; } .badge { position: absolute; top: 0; left: 0; z-index: 100; }

    Chrome DevTools renders the computed contrast ratio in the colour swatch of the Styles pane, below 4.5:1 it fails AA.

  5. 5Verify the layout at the real breakpoint

    @media (max-width: 768px) { .nav { display: none; } }

    This returns the boolean the browser actually uses for the media query, which settles off-by-one breakpoint disagreements.

  6. 6动画性能核对

    .box { transition: transform 0.3s ease; } .box:hover { transform: translateX(10px); }

    transition 与 hover 都作用在 transform 上时,动画只做合成不重排,帧率平稳。若换成 transition: all 或改 width 就会掉帧——先用 transform 版对比确认瓶颈是否在重排。

Command Examples

box-sizing decides whether width includes padding

* { box-sizing: border-box; } .card { width: 100%; padding: 20px; border: 1px solid #000; }

Under the default content-box, 100% width plus padding overflows the container by 40px. A global border-box makes width the final occupied size, and the class of "I set 100% and it still breaks the layout" bugs disappears at once.

Centring on both axes with flexbox

.parent { display: flex; justify-content: center; align-items: center; }

justify-content handles the main axis (horizontal) and align-items the cross axis (vertical); the division never changes. align-items defaults to stretch, so switching it to centre often collapses or stretches children, producing the classic "it got distorted once centred" effect.

Laying out a page with named grid areas

.layout { display: grid; grid-template-areas: "header" "main" "footer"; } .header { grid-area: header; } .main { grid-area: main; } .footer { grid-area: footer; }

Spaces inside the quotes are columns and newlines are rows, so "header main footer" means three columns in one row. Restructuring the layout means editing the areas string rather than recomputing grid-row and grid-column numbers one by one.

Fluid type with clamp

h1 { font-size: clamp(1rem, 2vw, 2rem); }

clamp(min, preferred, max) interpolates linearly between 375px and 1000px of viewport width, which beats a pile of media queries. Making the middle term a large multiple of vw (such as 5vw) overflows the container on small screens.

A sticky header with a z-index

.header { position: sticky; top: 0; z-index: 100; background: #fff; }

sticky needs a top or bottom reference, and an ancestor with overflow: hidden makes it stop sticking early inside that container. z-index is only compared between positioned elements, so writing it without a position has no effect.

Common Pitfalls

  • display: none removes the element and its subtree from layout, while visibility: hidden only makes it invisible but still occupies space; fading out with display collapses layout and lets clicks pass through to the layer below.
  • Without box-sizing: border-box, width and height exclude padding and border, so any percentage width plus padding overflows the parent — the usual root cause of misplaced layouts.
  • position: absolute resolves against the nearest positioned ancestor, not the viewport; remove that ancestor position and the element relocates to the initial containing block.
  • opacity creates a new stacking context: an ancestor with opacity and z-index: 999 can no longer be out-stacked by a child with a larger z-index.
  • vh includes the mobile browser address bar, so 100vh leaves the bottom of the page hidden behind it and produces an unscrollable strip of blank space.
  • transform and filter create containing blocks, which makes a nested position: fixed behave as absolute; animating an overlay makes it drift with the scroller.

Tips

  • box-sizing: border-box makes width/height include border and padding — more intuitive.
  • Flex fits one-dimensional layouts (row or column); Grid fits two-dimensional (rows and columns together).
  • Mobile-first: write small-screen styles first, then extend with @media (min-width).

FAQ

Why does a child with position: absolute end up in the wrong place?

Absolute positioning resolves against the nearest positioned ancestor, not the parent element itself. If the parent is position: static (the default), absolute falls back to the viewport, which is why the offset appears to do nothing. Give the intended container position: relative, offset the child with top/right/bottom/left, then use z-index: 100 to order it against siblings. fixed also resolves against the viewport, and sticky needs a scrolling ancestor — do not mix those reference frames up.

Does the choice between display: none and visibility: hidden change the layout?

Yes — that is the whole difference. display: none removes the element from the render tree so it occupies no layout space and later elements shift up; visibility: hidden only stops painting while the box keeps its place in the flow; opacity: 0 likewise keeps the space. Only display: none actually takes the element out, so when you toggle visibility conditionally and must not cause reflow, visibility: hidden or opacity: 0 is the safer choice.

When should I reach for Flex and when for Grid?

Pick by dimensionality. One-dimensional — a single row or column — is display: flex: flex-direction sets the main axis, justify-content aligns along it, align-items across it, flex-wrap allows wrapping, gap supplies spacing and flex: 1 shares out the remaining room. Two-dimensional is display: grid: grid-template-columns / rows define the skeleton, grid-column: 1 / 3 spans columns, and grid-template-areas lays out named regions. Do not use Grid for a one-axis job, and do not nest Flex containers to fake a grid.

How do I keep responsive CSS from turning into a pile of media queries?

Go mobile-first: write the small-screen styles as the default first, then extend upward with @media (min-width: 768px) { } instead of stacking max-width overrides. Use max-width: 100% on images and containers so nothing overflows, and min-width: 0 on flex children so they can actually shrink. Let type scale on its own with clamp(1rem, 2vw, 2rem), and choose units deliberately — vw/vh for the viewport, rem against the root, em against the parent.

What exactly does box-sizing: border-box change, and why set it globally?

Under the default content-box, width: 100px describes the content only, so once padding and border are added the element occupies more than 100px — which is why layouts overflow their containers. With box-sizing: border-box the declared width already includes padding and border, so the value matches the real footprint and works predictably with max-width: 100%. Set it once globally on the * selector instead of adjusting each box by hand.

Official References

Each command links to its official documentation below, so you can verify the latest usage and read deeper.

Maintained by LaoHand

Publicly updated on Jul 21, 2026, continuously proofread against official docs.

Contact Us

Wrong command or description? Send us corrections, business inquiries or product feedback by email.

Contact Us