In CSS, how can I set the border around what is displayed instead of what it occupies?

In CSS, how can I set the border around what is displayed instead of what it occupies?

I have a div containing an image. I want the image, regardless of whether it's larger or smaller than the div containing it, to be as large as possible so it fits within the div without changing the aspect ratio. I can achieve this with my code, but I also want to put a border around the image. By doing this, the border surrounds the entire container and not just the displayed image. What's the solution? Thanks in advance.

Here is my code:

<div class="divClass">
    <img class="imgClass" src="url_of_image" />
</div>

.divClass{
    position: absolute;
    top: 15%;
    width: 32%;
    height: 82.5%;
    display:flex;
    align-items:center;
    justify-content: center;
}

.imgClass{
    width: 100%;
    height: 100%;
    border: 1px solid rgb(118, 180, 255);
    object-fit: contain;
}

Here I put 2 sample images:

Example 1 Example 2

I would like, as I say, for the border to be around and attached to the images.

Answer

Use max-height/width instead.

.divClass {
  position: absolute;
  top: 5%;
  width: 32%;
  height: 82.5%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.imgClass {
  max-width: 100%;
  max-height: 100%;
  border: 6px solid rgb(118, 180, 255);
  object-fit: contain;
}
<div class="divClass">
  <img class="imgClass" src="https://s3.amazonaws.com/baconmockup/img/baconmockup-470-300.jpg" />
</div>

Enjoyed this question?

Check out more content on our blog or follow us on social media.

Browse more questions