CSS Height and Width Solution including max width and aspect ratio
The CSS height and width properties are used to set the height and width of an element. The CSS max-width property is used to set the maximum width of an element. The height and width properties do not include padding, borders, or margins. It sets the height/width of the area inside the padding, border, and margin of the element.
The height and width properties may have the following values:
- auto - This is default. The browser calculates the height and 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 - The height/width will be inherited from its parent value
Example
Set the height and width of a <img> element:
div {
height: 200px;
width: 50%;
background-color: green;
}
How to set max-width?
The max-width property is used to set the maximum width of an element. The max-width can be specified in length values, like px, cm, etc., or in percent (%) of the containing block, or set to none (this is default which means that there is no maximum width).
The problem with the <div> above occurs when the browser window is smaller than the width of the element (500px). The browser then adds a horizontal scrollbar to the page.
Using max-width instead, in this situation, will improve the browser's handling of small windows.
Tip: Drag the browser window to smaller than 500px wide, to see the difference between the two divs! This element has a height of 100 pixels and a max-width of 500 pixels.
Note: If you for some reason use both the width property and the max-width property on the same element, and the value of the width property is larger than the max-width property; the max-width property will be used (and the width property will be ignored).
Example
This <div> element has a height of 100 pixels and a max-width of 500 pixels:
div {
max-width: 500px;
height: 100px;
background-color: red;
}
How to set Aspect Ratio?
The aspect ratio of an element describes the proportional relationship between its width and its height. Two common video aspect ratios are 4:3 (the universal video format of the 20th century), and 16:9 (universal for HD television and European digital television, and default for YouTube videos). Learn how to maintain the aspect ratio of an element with CSS.
HTML Code:
<div class='element'>
<div class='content'>Aspect ratio of 1:1</div>
</div>
The CSS:
.element {
position: relative;
width: 50%; /* desired width */
}
.element:before {
content: "";
display: block;
padding-top: 100%; /* initial ratio of 1:1*/
}
.content {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
/* Other ratios - just apply the desired class to the "element" */
.ratio2_1:before {
padding-top: 50%;
}
.ratio1_2:before {
padding-top: 200%;
}
.ratio4_3:before {
padding-top: 75%;
}
.ratio16_9:before {
padding-top: 56.25%;
}