CSS Dimensions & Spacing
Controlling the space inside and around elements is crucial for clean layouts. In this guide, you’ll learn how to use width
, height
, margin
, and padding
effectively—and when to avoid common layout traps.
Width and Height
.tutorials-card {
width: 300px;
height: 200px;
}
Units You Can Use:
- Absolute:
px
,cm
,mm
,in
- Relative:
%
,em
,rem
,vw
,vh
,vmin
,vmax
auto
: default/depends on content
Best Practices
- Use
%
for responsive containers. - Use
max-width
instead of fixed width:
.tutorials-section {
max-width: 1240px;
width: 100%;
}
Padding vs Margin
Property | Affects | Creates Space… |
---|---|---|
padding | Inside the element | Between content & border |
margin | Outside the element | Between this and next element |
🔹 Padding Example
.tutorials-card {
padding: 20px;
}
Shorthand:
padding: 10px 20px; /* top-bottom, left-right */
padding: 10px 15px 5px 0; /* top, right, bottom, left */
Margin Example
.tutorials-card {
margin: 20px;
}
Shorthand:
margin: 10px auto; /* center horizontally */
Tips & Best Practices
✅ Use max-width
for containers instead of fixed width
✅ Avoid setting both width
and padding
without box-sizing control
✅ To center blocks: use margin: 0 auto;
✅ Watch for margin collapse
in vertical layouts
✅ Use rem
or em
for scalable spacing in modern designs
✅ Always reset or control box sizing:
* {
box-sizing: border-box;
}
✅ Real Example
.tutorials-section {
max-width: 1240px;
margin: 0 auto;
padding: 2rem;
}
.tutorials-card {
width: 100%;
padding: 1.5rem;
margin-bottom: 2rem;
box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}
✅ Summary Covered
width
,height
,max-
,min-
,auto
- Absolute and responsive units
- Difference between
margin
andpadding
- Spacing shorthand and tips
- Best practices to avoid layout bugs