Alexander6RI
Alexander6RI

Reputation: 11

Scrollbar creating empty space in div

Fiddle: https://jsfiddle.net/Alexander6RI/vpeasg1t/

I have an image which resizes to fill the height of its parent div, and the parent div has its width set to min-content. This works as expected.

When a horizontal scrollbar is added, the image correctly resizes to keep its aspect ratio while filling the available height. The problem is, the parent div continues to behave as if the image were full size which creates an empty space to the right. The intended function would be for the div to become narrower, because it has width: min-content, but it doesn't.

Is this an intended feature to improve document flow? Is there a way to make it follow the expected behavior?

Upvotes: 1

Views: 1572

Answers (2)

Wolfetto
Wolfetto

Reputation: 1130

You can probably use the object-fit css property like this:

.parent {
    outline: 2px solid black;
    width: min-content;
    height: 50vmin;
    resize: vertical;
    overflow-y: auto;
}
.child {
    outline: 2px solid red;
    height: 100%;
    object-fit: cover;
    display: block;
}

With cover value you can maintain the aspect ratio using all of image's parent space (the image will be adapted to the new space).

Upvotes: 0

Riunge Maina
Riunge Maina

Reputation: 542

The width is fine, it works as it should. The problem is the height, the height of the horizontal scroll bar is taken from the height: 50vmin; so the new height of the but the image tries to maintain its aspect ratio so it gets squashed down. Even though the height changes, (because again, the height of the horizontal scroll bar takes up some part of the parent's height.) the viewport doesn't so the height stays constant.

.parent {
    outline: 2px solid black;
    width: min-content;
    resize: vertical;
    overflow-y: auto;
}
.child {
    outline: 2px solid red;
    height: 100%;
    width: auto;
    display: block;
}

But if you need the height you might need to set the height of the parent and the child to be the same value then set the overflow to hidden like so

.parent {
    outline: 2px solid black;
    width: min-content;
    resize: vertical;
    height: 50vmin;
    overflow:hidden;
}
.child {
    outline: 2px solid red;
  height: 50vmin;
    width: auto;
    display: block;
}

A fraction of the image gets clipped at the bottom but that's the best solution I can think of.

Upvotes: 2

Related Questions