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 */
}
CSS Height and Width – Interview Questions
Q 1: What do height and width properties do?
Ans: They define the size of an element.
Q 2: Can height and width be auto?
Ans: Yes, auto adjusts based on content.
Q 3: What units are used for height and width?
Ans: px, %, vw, vh.
Q 4: What is max-width?
Ans: It limits the maximum width of an element.
Q 5: Why is max-width preferred for responsive design?
Ans: It prevents layout overflow on small screens.
CSS Height and Width – Objective Questions (MCQs)
Q1. Which property sets the height of an element?
Q2. Which property sets the width of an element?
Q3. Which unit is relative to the viewport width?
Q4. Which value sets automatic width?
Q5. Which property limits the maximum width?