CSS Tutorial
CSS Height / Width
The height and width properties control the size of an element's content area. CSS also gives you min and max limits to keep elements flexible and responsive.
Setting height and width
The width and height properties set how wide and tall an element's content area is. You can use fixed units like pixels, or relative units like percentages, which size the element based on its parent.
<!DOCTYPE html>
<html>
<head>
<style>
.box {
width: 250px;
height: 120px;
background-color: #2b5cff;
color: white;
padding: 12px;
font-family: Arial, sans-serif;
}
</style>
</head>
<body>
<div class="box">250px wide, 120px tall</div>
</body>
</html>Percentage sizing
A width in percent is relative to the parent element. width: 50% means half the width of the container. This is the foundation of layouts that adapt to different screen sizes.
<!DOCTYPE html>
<html>
<head>
<style>
.half {
width: 50%;
background-color: tomato;
color: white;
padding: 12px;
font-family: Arial, sans-serif;
}
</style>
</head>
<body>
<div class="half">I am 50% of my parent's width. Resize the window!</div>
</body>
</html>min and max limits
Fixed sizes can break on small screens. The max-width and min-width properties (and their height equivalents) set limits so an element grows and shrinks within a safe range. max-width is especially useful for keeping text columns readable.
.content {
width: 100%;
max-width: 700px; /* never wider than 700px */
margin: 0 auto;
}Sizing properties reference
| Property | Purpose | Example |
|---|---|---|
| width | Content width | 250px or 50% |
| height | Content height | 120px |
| max-width | Largest allowed width | 700px |
| min-width | Smallest allowed width | 200px |
| max-height / min-height | Height limits | 400px |
The combo width: 100%; max-width: 700px; margin: 0 auto; is a classic recipe for a centered, responsive content area that never gets too wide to read.
By default, width sets only the content area, so borders and padding are added on top. Use box-sizing: border-box to make width include padding and border.
Key points
- width and height set the content area size.
- Percentages are relative to the parent element.
- max-width and min-width keep elements flexible.
- max-width helps keep text columns readable.
- By default, padding and borders add to the set size.
