Sizing elements is one of the first things you will do in CSS. But width and height come with a few surprises.
width and height
These set the dimensions of the content area. Block elements stretch to fill their container by default, but you can give them a specific size:
.box {
width: 300px;
height: 200px;
}
Try it Yourself →
Remember that width and height only set the content area. The actual space is larger once you add padding, border, and margin.
Percentage Sizing
Percentages are relative to the parent element:
.child {
width: 50%; /* half the parent's width */
height: 50%; /* half the parent's height */
}
Percentage heights can be tricky — they only work if the parent has a defined height. If the parent's height is auto, the percentage is ignored.
max-width and min-width
Sometimes you want an element to be flexible but not too much. That is where max-width and min-width come in:
.container {
width: 100%;
max-width: 800px;
min-width: 300px;
}
This container stretches to fill the screen, but stops at 800px on wide screens. On narrow screens, it shrinks but never below 300px. This pattern is the foundation of responsive design.
Fixed vs Fluid
Fixed sizes (pixels) stay the same no matter the screen. Fluid sizes (percentages, viewport units) adjust to the container.
.fixed { width: 400px; } /* always 400px */
.fluid { width: 50%; } /* half the parent, changes with screen size */
Neither is right or wrong — use fixed for things like sidebars or cards, and fluid for layouts that need to adapt.