CSS Reference ยท Custom Properties, Cascade and Global Keywords
Shorthand properties
How CSS shorthand properties work: expansion to longhands, omitted values resetting to initial, the 1-2-3-4 value pattern, and common traps, with live examples.
A shorthand property sets several related longhand properties in one declaration. margin sets margin-top, margin-right, margin-bottom and margin-left; border sets nine longhands (width, style and color for each side); background sets eight or more.
The shorthand is not only shorter. It also has one rule that catches people out: any longhand you leave out is reset to its initial value, not left alone.
Try it
The 1-2-3-4 pattern
Box shorthands such as margin, padding, border-width, border-color, border-style, inset and scroll-margin take one to four values and go clockwise from the top:
| Values | Meaning |
|---|---|
a |
all four sides |
a b |
top and bottom = a; left and right = b |
a b c |
top = a; left and right = b; bottom = c |
a b c d |
top, right, bottom, left |
Corner shorthands like border-radius follow the same idea starting at the top-left corner. A slash separates horizontal and vertical radii.
Usage notes
- Order often matters less than you think:
border: 1px solid red,border: red solid 1pxandborder: solid 1px redmean the same, because the value types are distinct. Where types overlap (for examplefont,background-positionwithbackground-size) the syntax is stricter:fontneeds size before family, andbackground-sizefollows/after position. fontresets a lot: it also resetsline-height,font-variantsubproperties,font-stretchand others unless you give them.- Cascade effect. A shorthand later in the cascade overrides the earlier longhands it covers, as in the demo. Put shorthands before longhands, not after, if you want both.
allis the extreme shorthand: it resets every property exceptdirection,unicode-bidiand custom properties.- Invalid values drop the whole declaration. One bad value in a shorthand means nothing is applied.
- Logical shorthands:
margin-inline,padding-block,inset-inlineand friends are shorthands for logical longhands. - Reading values in JavaScript:
getComputedStyle(el).marginmay be an empty string in some browsers when the four sides differ; read the longhands (marginTop) for reliable results. - Animation and transition shorthands set many longhands at once, including
animation-delay; a missing item resets to its initial value.
Related
margin,padding,border,background,font,allcascade and specificity- Lessons: Margins, Padding