CSS Height and Width
Width and height are properties that set the size of an element's content area. A value in percent is a share of the parent element's size.
Set a fixed size
The width and height values fix the content area of the box. The values count pixels.
.box {
width: 300px;
height: 100px;
}Half the parent width
The percent value makes the box half as wide as its parent. The box resizes when the parent resizes.
.box {
width: 50%;
}Cap the width
The width asks for 900 pixels. The max-width value caps the result at 400 pixels.
.box {
width: 900px;
max-width: 400px;
}Example
.box {
width: 50%;
height: 120px;
max-width: 350px;
}
p.intro {
width: 100px;
min-width: 200px;
}Key points
- width: the property that sets the content width
- height: the property that sets the content height
- A percent value is a share of the parent element's size.
- max-width: the property that caps how wide an element can grow
- min-width: the property that sets the smallest width an element can take
- The default height value auto lets the box grow with its content.
- A percent height needs a parent element with a set height.
In this example, the box asks for half the width of its parent. Its max-width caps that share at 350 pixels. Its height is fixed at 120 pixels. The intro paragraph asks for 100 pixels, and its min-width lifts the result to 200 pixels.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does the max-width property do?