Center and scale image in div

  Kiến thức lập trình

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>

New contributor

user24549087 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

0

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>

LEAVE A COMMENT