
CSS
CSS Height & Width
The height and width properties define the height and width that an element will have. These properties determine the height and width of an element, which in turn affects its position and layout within a document.
.box {
width: 400px;
height: 150px;
}
Setting Height and Width Values
By setting the height and width of an element, a developer can define the dimensions of a particular element. It can be applied to block-level elements, inline-block elements, and replaced elements such as images.
- The element’s height and width properties are only for the content area. It does not include CSS padding, borders, or margins. It only sets the height and width of the elements inside these areas.
.content-box {
width: 200px;
height: 100px;
background-color: lightgreen;
padding: 20px;
border: 5px solid green;
margin: 20px;
}
Height and Width Values
The information below provides details about the height and width properties of a CSS element.
- Auto: Using this default setting, you can set an element’s height and width according to its content.
- Length: Defines the height and width of an element using units such as px, em, rem, and others.
- Percentage: Based on the parent element’s percentage, the element’s height and width are chosen or set.
- Min-content: With this, an element’s width is set to the minimum width required by its content to prevent overflowing.
- Max-content: It is used to adjust an element’s width to the maximum that fits the longest content without causing it to wrap.
- Initial: It resets the height or width of the element to the default setting of the browser.
- Inherit: Applies the height or width from the element’s parent by inheriting its value.
.parent {
width: 400px;
height: 200px;
border: 2px solid #333;
padding: 10px;
margin-bottom: 20px;
}
.auto-box {
width: auto;
height: auto;
}
.length-box {
width: 150px;
height: 80px;
}
.percent-box {
width: 50%;
height: 50%;
}
.min-box {
width: min-content;
}
.max-box {
width: max-content;
}
.initial-box {
width: initial;
height: initial;
}
.inherit-box {
width: inherit;
height: inherit;
}
Setting CSS Max-Width
This property is used to define the maximum width an element can occupy. It is defined in various length values such as px, cm, or percentage. By default, it is set to none, which means no maximum width.
.container {
width: 100%;
border: 2px solid #333;
padding: 10px;
box-sizing: border-box;
}
.box {
max-width: 500px;
background-color: lightcoral;
color: white;
padding: 20px;
margin: 0 auto;
}
In above example, the box has a max-width of 500px. It will grow to fit 100% of its container, but will not exceed 500px in width even on larger screens.
When both the width property and max-width property are used on the same element, the max-width property will be considered even if its width property is larger than the max-width.