CSS Width and Height
Control element dimensions and sensible size limits.
Width and Height
CSS width and height properties control the size of an element. They can be used for boxes, images, buttons, sections, and other HTML elements.
.card {
width: 300px;
height: 200px;
}This creates a card that is 300px wide and 200px high.
The width Property
The width property controls the horizontal size of an element.
.banner {
width: 500px;
}You can use different CSS units:
.fixed-box {
width: 300px;
}
.flexible-box {
width: 80%;
}
.full-screen-box {
width: 100vw;
}pxcreates a fixed width.%calculates the width from the parent element.vwcalculates it from the viewport width.remcreates a size based on the root font size.
The height Property
The height property controls the vertical size of an element.
.hero {
height: 400px;
}You can also create a full-screen section:
.hero {
height: 100vh;
}Here, 100vh means 100% of the viewport height.
Be careful when setting a fixed height for text containers. If the content becomes too large, it may overflow.
Automatic Sizing
The default value of width and height is usually auto. It allows the browser to calculate the required size.
article {
width: auto;
height: auto;
}With height: auto, the element grows when more content is added. This is often better than using a fixed height.
Minimum Width and Height
The min-width and min-height properties set the smallest allowed size.
.card {
min-width: 250px;
min-height: 150px;
}These properties are helpful when an element must not become too small.
For example:
button {
min-width: 120px;
min-height: 44px;
}The button can grow when its text changes, but it will not become smaller than the given values.
Maximum Width and Height
The max-width and max-height properties limit how large an element can become.
.container {
width: 90%;
max-width: 1200px;
}This container:
- Uses 90% of the available width.
- Stops growing after reaching
1200px. - Remains flexible on smaller screens.
A common responsive image rule is:
img {
max-width: 100%;
height: auto;
}The image becomes smaller when needed while keeping its original proportions.
Handling Overflow
Content may not fit when an element has a fixed width or height. Use overflow to control what happens.
.description {
width: 300px;
height: 120px;
overflow: auto;
}Common values include:
visible– displays overflowing contenthidden– hides extra contentscroll– always adds scrollbarsauto– adds scrollbars only when required
Width, Height, and the Box Model
By default, width and height apply only to the content area. Padding and borders are added to the final size.
* {
box-sizing: border-box;
}With border-box, the declared size includes the content, padding, and border. This makes element sizing easier to manage.