The height and width properties in CSS are fundamental for controlling the size of HTML elements. Whether you’re creating simple layouts or complex responsive designs, understanding how these properties work is essential to building well-structured, user-friendly web pages.
In this article, we’ll explore what the height
and width
properties are, how they behave, the units you can use, and some common best practices.
π What Do Height and Width Do?
The height
and width
properties define the vertical and horizontal dimensions of an element’s content box. These properties affect how much space an element occupies in the layout.
Basic Syntax:
.element {
width: 300px;
height: 150px;
}
This sets a fixed size for the .element
.
π§± Content Box vs Border Box
By default, CSS uses the content-box model, meaning:
width
andheight
only apply to the content, not padding, border, or margin.- The actual size of the element is larger if you add padding or borders.
To include padding and borders in the declared dimensions, use:
* {
box-sizing: border-box;
}
With border-box
, width
and height
define the entire element size.
π Units You Can Use
You can set height and width using various CSS units:
β Absolute Units:
px
(pixels)cm
,mm
,in
,pt
(mainly for print)
β Relative Units:
%
(percentage of the parent element)em
,rem
(relative to font size)vw
,vh
(viewport width/height)vmin
,vmax
(relative to the smaller/larger viewport dimension)
.container {
width: 100%;
height: 100vh;
}
π Auto, Max, and Min Values
auto
The default value β lets the browser determine size based on content.
.box {
width: auto;
}
min-width
/ max-width
Used to set size boundaries for responsive behavior.
img {
max-width: 100%;
height: auto;
}
This ensures images scale responsively but donβt exceed their container size.
π§ Special Considerations
- Height percentages require the parent to have an explicitly defined height.
- Inline elements (like
<span>
) ignorewidth
andheight
unless changed todisplay: inline-block
,block
, orflex
. - Use media queries to adjust width/height on different screen sizes.
β Summary
The height
and width
properties are essential tools in CSS layout design. They help define how much space elements occupy, respond to various screen sizes, and work hand-in-hand with other layout techniques like Flexbox and Grid.
Quick Recap:
width
andheight
set horizontal and vertical dimensions.- Use units like
px
,%
,em
,vw
,vh
. box-sizing
affects how these values are calculated.- Use
min-
andmax-
to create responsive constraints.