Episode 38 of 53
Padding and Margin Longhand
Understand the shorthand vs longhand syntax for padding and margin properties.
CSS provides both shorthand and longhand syntax for padding and margin. Understanding both helps you write cleaner, more maintainable CSS.
Longhand Properties
/* Longhand — explicit and clear */
.box {
margin-top: 10px;
margin-right: 20px;
margin-bottom: 10px;
margin-left: 20px;
padding-top: 1rem;
padding-right: 1.5rem;
padding-bottom: 1rem;
padding-left: 1.5rem;
}
Shorthand Patterns
/* 1 value: all sides */
margin: 10px; /* T=10, R=10, B=10, L=10 */
/* 2 values: vertical | horizontal */
margin: 10px 20px; /* T=10, R=20, B=10, L=20 */
/* 3 values: top | horizontal | bottom */
margin: 10px 20px 30px; /* T=10, R=20, B=30, L=20 */
/* 4 values: top | right | bottom | left (clockwise) */
margin: 10px 20px 30px 40px;
When to Use Which
- Shorthand — when setting all or most sides at once
- Longhand — when only changing one side, or for clarity
/* Good: shorthand for setting all sides */
.card { padding: 1.5rem; }
/* Good: longhand to override just one side */
.card-compact { padding-top: 0.75rem; }
/* Avoid: shorthand that resets other values unintentionally */
.card { padding: 1.5rem; }
.card { padding: 0.5rem 1.5rem; } /* Oops — changed top and bottom! */
Tip: The Clockwise Mnemonic
Think of a clock: Top → Right → Bottom → Left (TRouBLe).