skip to Main Content

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


  1. 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:

    html, body {
      height: 100%;
    }
    
    html, body {
      height: 100%;
    }
    
    img {
        width: 70%;
        max-height: 50%;
        display: block;
        margin-left: auto;
        margin-right: auto;
    }
    <img src="https://picsum.photos/200/300?grayscale&blur=1">

    Or you could use the viewport height vh unit: max-height: 50vh

    img {
      display: block;
      margin: auto;
      width: 70%;
      max-height: 50vh;
    }
    <img src="https://picsum.photos/200/300?grayscale&blur=1">
    Login or Signup to reply.
  2. 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".

    max-height: 40vh;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search