I’m have an image which is limited to 70% of the screen size. This is great for mobile or tiled displays. However, for full screen the image takes up almost all of the screen. Therefore, I would like to restrict the image to take up at most 40% of the height of the screen.
My current code is:
.test_image {
width: 70%;
max-height: 50%;
display: block;
margin-left: auto;
margin-right: auto;
}
However, the max-height
doesn’t appear to have any effect, if I make the browser wide and short then the image still takes up the full height of the screen.
What am I doing wrong and how do I fix it?
2
Answers
The percentage is not a portion of the screen but of the parent container. In this basic example, the parent container (
body
) defaults to the size of the content because there is no declared dimensions.You could declare a height for the parent and root elements:
Or you could use the viewport height
vh
unit:max-height: 50vh
Since the max-height property in CSS is relative to the height of the parent element, not the viewport.
If you want to limit the height of the image to a percentage of the viewport height, you could use the vh unit, which stands for "viewport height".