CSS Max Height
What is Max Height in CSS?
Max-height property will decide the limiting height of an element.
Such feature is often applied to develop a responsive design, for example, when there is a need to constrain the extension of pictures or other containers/blocks to a specific height.
Basic Usage:
This is the instance that is a maximum height for flex items within a flex container.
img {
max-height: 200px; /* Set the maximum height of the image to 200 pixels */
}
Responsive Image with Max Height:
This example makes an image responsive by setting its maximum height to 100% of its containing element. The width is set to auto to maintain the aspect ratio.
img {
max-height: 100%;
width: auto; /* Maintain the aspect ratio while resizing based on the container's width */
}
Max Height for a Container:
This sets the maximum height for a container, and if the content inside the container exceeds this height, a scrollbar will appear.
.container {
max-height: 300px; /* Set the maximum height of a container to 300 pixels */
overflow: auto; /* Add a scrollbar if the content overflows the container */
}
Responsive Text with Max Height:
This example limits a paragraph's height to the equivalent of 3 lines of text and hides any overflow.
p {
max-height: 3em; /* Set the maximum height for a paragraph to 3 lines of text */
overflow: hidden; /* Hide any content that overflows the specified height */
}
Max Height with Flexbox:
This example sets the maximum height for flex items within a flex container.
.container {
display: flex;
flex-direction: column;
}
.item {
max-height: 100px; /* Set the maximum height of flex items */
overflow: auto; /* Add a scrollbar if the content overflows the item */
}
Aspect Ratio with Max Height:
In this instance max-height alongside object-fit is used separately to set responsive video element with preserved aspect proportion.
.container {
max-height: 300px; /* Set the maximum height of the container */
}
.video {
width: 100%;
height: 100%;
object-fit: cover; /* Maintain aspect ratio and cover the container */
}