Box Model and Spacing
Understanding how to control spacing, margins, borders, and element dimensions is key to building consistent user interfaces. Let us explore how Tailwind CSS manages the box model.
1. Margin and Padding Utilities
Tailwind provides a logical scale for margins (m-) and paddings (p-). The spacing values map directly to a rem scale, where 1 unit equals 0.25rem (typically 4px in default browser setups).
Axis Directions
You can target specific sides or axes by appending letters:
t: Top (e.g.,pt-4sets padding-top to 1rem)b: Bottom (e.g.,mb-2sets margin-bottom to 0.5rem)l: Left (e.g.,ml-6sets margin-left to 1.5rem)r: Right (e.g.,pr-1sets padding-right to 0.25rem)x: Horizontal axis (both left and right, e.g.,mx-autocenters a block horizontally)y: Vertical axis (both top and bottom, e.g.,py-8sets vertical padding to 2rem)
2. Width and Height Dimensions
Tailwind offers multiple ways to set element sizes using fractions, fixed values, or dynamic viewport units:
Fixed Sizes
w-64: Width of 16rem (256px).h-12: Height of 3rem (48px).
Percentage Fractions
w-1/2: Width of 50%.w-3/4: Width of 75%.w-full: Width of 100%.
Viewport Scales
h-screen: Height of 100vh (full browser window height).w-screen: Width of 100vw.
3. Borders and Box-Sizing
By default, Tailwind configures all elements to use box-sizing: border-box. This means borders and padding are included in the total width and height calculations.
You can customize borders with these utility classes:
- Border Width:
border(1px),border-2(2px),border-4(4px). - Border Color:
border-gray-200,border-blue-500. - Border Style:
border-solid,border-dashed.