In CSS, the height
and width
properties are used to set the height and width of an element. Here’s a detailed guide on how to use these properties:
Syntax: for height
height: value;
Syntax: for Width
width: value;
Values of height and width
auto: Default value. The browser calculates the height/width.
length: Defines the height/width in px, cm, etc.
%: Defines the height/width in percent of the containing block.
initial: Sets the height/width to its default value.
inherit: Inherits the height/width from its parent element.
Examples
1. Fixed Height and Width:
.box {
height: 200px;
width: 300px;
border: 1px solid #000;
}
2. Percentage-Based Height and Width:
.container {
height: 100%; /* Takes up 100% of the parent's height */
width: 50%; /* Takes up 50% of the parent's width */
border: 1px solid #000;
}
3. Height and Width with Auto Value:
.box {
height: auto; /* Automatically calculated height */
width: auto; /* Automatically calculated width */
border: 1px solid #000;
}
4. Using max-width
and max-height
:
.image {
max-width: 100%; /* Ensures the image does not exceed the container's width */
max-height: 100%; /* Ensures the image does not exceed the container's height */
}
min-width
and min-height
Use min-width
and min-height
to set the minimum dimensions an element can have.
.box {
min-height: 100px;
min-width: 200px;
border: 1px solid #000;
}
max-width
and max-height
Use max-width
and max-height
to set the maximum dimensions an element can have.
.box {
max-height: 300px;
max-width: 400px;
border: 1px solid #000;
}
box-sizing
The box-sizing
property can affect the actual rendered dimensions of an element by including/excluding padding and border in the element’s total width and height.
.box {
width: 300px;
height: 200px;
padding: 20px;
border: 10px solid #000;
box-sizing: border-box; /* Ensures the padding and border are included in the width and height */
}