CSS Dimensions
Learn how to control the size of elements using CSS width, height, and related properties
What are CSS Dimensions?
CSS dimensions control the size of elements on a web page. The main properties are width
and height
, but there are also related properties for setting minimums, maximums, and content-based sizing.
Key Dimension Properties:
- width - Sets the width of an element
- height - Sets the height of an element
- min-width - Sets the minimum width of an element
- max-width - Sets the maximum width of an element
- min-height - Sets the minimum height of an element
- max-height - Sets the maximum height of an element
- box-sizing - Defines how width and height are calculated
Dimensions in Action
Example Code
/* Width and Height Properties */ .element { /* Fixed dimensions */ width: 300px; height: 200px; /* Percentage dimensions (relative to parent) */ width: 50%; height: 75%; /* Viewport dimensions */ width: 50vw; /* 50% of viewport width */ height: 25vh; /* 25% of viewport height */ /* Minimum and maximum dimensions */ min-width: 100px; max-width: 500px; min-height: 50px; max-height: 300px; /* Auto dimensions (browser calculates) */ width: auto; height: auto; } /* Special dimension values */ .special { width: fit-content; /* As wide as the content needs */ height: fit-content; /* As tall as the content needs */ width: max-content; /* As wide as the maximum content width */ height: max-content; /* As tall as the maximum content height */ width: min-content; /* As wide as the minimum content width */ height: min-content; /* As tall as the minimum content height */ }
Units for CSS Dimensions
Absolute Units
Absolute units are fixed sizes that don't change based on other elements or screen size.
- px - Pixels (most common)
- cm - Centimeters
- mm - Millimeters
- in - Inches (1in = 96px)
- pt - Points (1pt = 1/72in)
- pc - Picas (1pc = 12pt)
Relative Units
Relative units are sized based on other elements or the viewport, making them great for responsive design.
- % - Percentage of parent element
- em - Relative to font size of element
- rem - Relative to font size of root element
- vw - 1% of viewport width
- vh - 1% of viewport height
- vmin - 1% of viewport's smaller dimension
- vmax - 1% of viewport's larger dimension
Content-Based Sizing
fit-content
Sizes the element to fit its content, but won't exceed the available space.
min-content
Uses the minimum size needed to contain the content without overflow.
max-content
Uses the maximum size needed to contain the content without wrapping or overflow.
Using Min and Max Dimensions
Minimum Dimensions
Use min-width
and min-height
to ensure elements don't become too small.
Maximum Dimensions
Use max-width
and max-height
to ensure elements don't become too large.
Pro Tip: Combine min and max dimensions for responsive containers that adapt to different screen sizes: