How to wrap a resizable div around a image using flexbox

Viewed 42

Im trying to wrap a div around a image both when the width or height changes.

The issue is that when the width changes the div does not tightly wrap against the child in this case the child is a image:

Wrap div around a image current result

I did determine that setting the flex-direction between row and column solves it when the div gets resized and could use something like a resize observer to toggle the flex direction but hope there is a css solution to this?

Here is a code pen with the issue: https://codepen.io/quinnaz/pen/rNJdjJy

<div class="container direction-row">
  <div class="border">
    <img src="https://dummyimage.com/400x600/d4b9d4/7477a3.png" class="img-element" />
  </div>
</div>

.container {
  resize: both;
  overflow: auto;
  background-color: beige;
  border: solid;
  display: flex;
}

.direction-row {
  flex-direction: row;
}
.direction-col {
  flex-direction: column;
}

.img-element {
  max-width: 100%;
  max-height: 100%;
  display: block;
}

.border {
  border-width: 50px;
  border-color: blue;
  border-style: solid;
}
1 Answers

You need to use the object-fit property and give it the value cover. I would also change max-width and max-height to width and height respectively.

The replaced content (in this case an image) is sized to maintain its aspect ratio while filling the element's entire content box. If the object's aspect ratio does not match the aspect ratio of its box, then the object will be clipped to fit.

codepen link https://codepen.io/thechewy/pen/ZErxevo

.img-element {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
}

** EDIT **

If you want it to fully fit the .container div you'll then need to make the .border div fill the parent .container with width: 100%; height: 100%; set on .border, this isn't clear in the question though. If not the above snippet should do the trick.

Personally I would just add the border to the image and remove the extra div and CSS.

Related