skip to Main Content

I’m quite new to CSS and trying to achieve the following (with pure CSS):
I have a fixed div spanning the whole view (container-outer-01).
Inside it, I would like to place another div (container-inner-01) with an image inside.
The second div should be exactly the same size as the image and behave like "object-fit: contain": scale as large as possible without losing the original aspect ratio.

I have the following simple HTML structure (can’t change the inner div and the img):

.container-outer-01 {
  position: fixed;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.container-inner-01 {
  max-height: 100%;
  max-width: 100%;
  overflow: hidden;
  border-radius: 20px;
  outline: dashed red;
}

.container-inner-01 img {
  height: 100%;
  max-height: 100%;
  max-width: 100%;
}
<div class="container-outer-01">
  <div class="container-inner-01">
    <img src="https://placehold.co/600x400">
  </div>
</div>

2

Answers


  1. Just give the img a display: block. Inline elements have different bounding boxes than block elements.

    .container-outer-01 {
      position: fixed;
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .container-inner-01 {
      max-height: 100%;
      max-width: 100%;
      overflow: hidden;
      border-radius: 20px;
      outline: dashed red;
    }
    
    .container-inner-01 img {
      display: block;
      height: 100%;
      max-height: 100%;
      max-width: 100%;
    }
    <div class="container-outer-01">
      <div class="container-inner-01">
        <img src="https://placehold.co/600x400">
      </div>
    </div>
    Login or Signup to reply.
  2. You can also use display: flex to your container-inner-01 or your img (and don’t need max-width or max-height) just set width:100%

    .container-outer-01 {
      position: fixed;
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .container-inner-01 {
      max-height: 100%;
      max-width: 100%;
      overflow: hidden;
      border-radius: 20px;
      outline: dashed red;
    }
    
    .container-inner-01 img {
      display:flex;
      height: 100%;
      width:100%;
     }
    <div class="container-outer-01">
      <div class="container-inner-01">
        <img src="https://placehold.co/600x400">
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search