Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
CSS Width, Height & Sizing
Control how wide and tall elements are with width, height, max-width, min-height, and other sizing properties. Understanding these properties is essential for responsive layouts and predictable component sizing.
Sizing Properties
- width - Fixed width: width: 300px. Percentage: width: 50%. Auto: width: auto (default - fills parent for block elements)
- height - Fixed height: height: 200px. Usually leave as auto - content determines height
- max-width - Maximum width limit: max-width: 1200px. Element can be smaller but never wider
- min-width - Minimum width: min-width: 200px. Element can grow but never shrink below this
- max-height / min-height - Same concept for height. min-height: 100vh for full-screen sections
- width: 100% - Takes full width of parent. Different from width: auto (auto accounts for margins)
- Avoid fixed heights - Let content determine height. Fixed heights cause text overflow on different screens
Sizing in Practice
/* Responsive container */
.container {
width: 100%;
max-width: 1200px; /* Never wider than 1200px */
margin: 0 auto;
padding: 0 20px;
}
/* Full-screen hero section */
.hero {
min-height: 100vh; /* At least full screen */
/* Content can push it taller */
}
/* Responsive image */
img {
max-width: 100%; /* Never wider than parent */
height: auto; /* Maintain aspect ratio */
}
/* Card with fixed width */
.card {
width: 320px; /* Fixed width */
min-height: 200px; /* Minimum height */
/* Height grows with content */
}
/* Avoid this: */
.bad {
height: 300px; /* Fixed height = overflow risk! */
/* Text may overflow on small screens */
}Tip
Use min-height instead of height for sections with text content. min-height: 100vh makes a section at least full-screen but allows it to grow if content requires more space. Fixed height causes text overflow on mobile devices.
Every element follows the box model - content + padding + border + margin
Common Mistake
Setting height: 300px on containers with dynamic text content. When the text is longer than 300px (common on small screens), it overflows and overlaps other elements. Always use min-height instead of height for text-containing elements.
Quick Quiz
Key Takeaways
- Control how wide and tall elements are with width, height, max-width, min-height, and other sizing properties.
- width - Fixed width: width: 300px. Percentage: width: 50%. Auto: width: auto (default - fills parent for block elements)
- height - Fixed height: height: 200px. Usually leave as auto - content determines height
- max-width - Maximum width limit: max-width: 1200px. Element can be smaller but never wider