CSS width
and height
properties are used to set the width and height of an element.
This element has a height of 100px and a width of 50%.
The width and height of an element can be set in any valid CSS length format such as px, em, rem, cm, etc., or in %. The <div>
element in the example below has a width of 300px and height of 200px. Try it out:
Example:
div{ width: 300px; height: 200px; background: cyan; }
CSS height
and width
properties can accept any of the following values:
- length – defines width/height in px, em, rem, cm, pt, etc.
- auto – browser automatically calculates the suitable width/height(This is the default value).
- % – element has given % width/height of its parent element.
- initial – It sets the width/height to its default value, which is auto for width/height.
- inherit – element inherits width/height from its parent element.
Setting width and height using percentage(%)
The width and height of an element can also be specified in %. The % values are calculated from the width and height of the parent element.
In the example below, the child <div>
element takes up 50% width and 60% height of its parent <div>
element. Try out the example below to check how it works:
Example:
.parent{ width: 400px; height: 250px; } .child{ width: 50%; height: 60%; }
CSS Maximum Width and Height
CSS max-width
and max-height
properties are used to set maximum width and height of an element.
Similar to the width
and height
properties, the max-width
and max-heigh
t properties can also be specified in any valid CSS length format such as px, em, rem, cm, etc.
The width of the element can never exceed its max-width. The same applies to max-height also.
Setting Maximum Width
The <div>
element in the example below has a max-width of 400px. Try it out to see how it works:
Example:
div{ max-width: 400px; background: lightblue; }
Setting Maximum Height
Similar to the max-width
, you can set the max-height
property. If the value of the max-height is lower than the height, the element uses the max-height instead, if it is higher than the height value, it has no effect on the element. Try out the example below:
Example:
div{ height: 3000px; max-height: 100px; background: lightblue; }
All Width and Height Properties
Property | Description |
width | Sets the width of the element. |
height | Sets the height of the element. |
max-width | Sets the maximum width of an element. |
max-height | Sets the maximum height of an element. |
min-width | Sets the minimum width of an element. |
min-height | Sets the minimum height of an element. |