css – 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 and behave like “object-fit: contain”: scale as large as possible without loosing the original aspect ratio.

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

<div class="container-outer-01">
  <div class="container-inner-01">
    <img src="https://placehold.co/600x400">
  </div>
</div>

and tried this CSS (not working):

.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%;
}

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.

LEAVE A COMMENT