🌱BeginnerCSS Box Model
CSS Width and Height
Control element dimensions with width, height, min/max constraints, and understand how box-sizing affects them.
Overview
CSS lets you explicitly set the size of elements with `width` and `height`. You can use fixed values, percentages, or viewport units. You can also set minimum and maximum constraints.
- `width` / `height` exact size (100px, 50%, 20rem)
- `min-width` / `min-height` element cannot shrink below this size
- `max-width` / `max-height` element cannot grow beyond this size
The combination `width: 100%; max-width: 1200px` is the standard pattern for responsive containers: the element fills its parent on small screens but never exceeds 1200px on large screens.
For height, using `min-height` is often better than `height` because it allows the element to grow when content overflows.
`width: auto` (the default) lets the browser calculate the width. For block elements this fills the available width; for inline elements it shrinks to fit the content.
Key Points
- •width and height accept px, %, em, rem, vw, vh, auto, fit-content
- •max-width: 100% prevents elements from overflowing their container
- •min-height is safer than height for containers allows growth with content
- •width: 100%; max-width: 1200px; margin: 0 auto standard responsive container
- •height: 100vh makes an element fill the full viewport height
- •width: fit-content shrinks to wrap content without collapsing like inline
Examples
Responsive container pattern
.container {
width: 100%; /* fill parent on small screens */
max-width: 1200px; /* cap width on large screens */
margin: 0 auto; /* center horizontally */
padding: 0 16px; /* side gutters */
box-sizing: border-box;
}This is the most common layout pattern in web development.
Height patterns
/* Full viewport height hero */
.hero {
height: 100vh;
}
/* Minimum height grows with content */
.card {
min-height: 200px;
}
/* Constrain image height */
.thumbnail {
width: 100%;
height: 200px;
object-fit: cover; /* prevents distortion */
}Images and max-width
/* Images never overflow their container */
img {
max-width: 100%;
height: auto; /* maintain aspect ratio */
}"max-width: 100%; height: auto" on img is a foundational responsive images rule.
Common Mistakes
- Setting height on a container that holds text it overflows when content is longer than expected
- Forgetting height: auto on images when setting max-width aspect ratio distorts
- Using width: 100% without box-sizing: border-box and then adding padding causes overflow
Note
Avoid setting explicit height on containers. Use min-height for a minimum size and let content expand naturally. Fixed heights are fine for images, icons, and fixed UI components.
Exercises
Write CSS to style the HTML scaffold. The preview updates live — when it looks right, mark as done.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4