Home > Software engineering >  Flexbox container slightly taller than its contents
Flexbox container slightly taller than its contents

Time:09-28

I have a flex container with 4 columns/flex items, each containing an image of the same size/proportions with the max-width set to 100%. Columns have an overflow property set to hidden since I want to scale images on hover but don't want them to expand outside their column's "boundaries". However, the container's height is 382px while the image height is 379.5px leaving a subtle gap of 2.5px on the bottom when hovering image. Please refer to the modified screenshot below (red line marks the bottom edge of the container, second/lighter image is in hover state) as well as the code.

I've tried setting the flex container's align-items property to center and I've tried removing whitespace in HTML, among other things, to no avail. I am trying to wrap my head around what might be causing this discrapency. From what I understand, the height of elements in CSS is determined by their children so I don't get why it's 382px in the first place if the height of each image is 379.5px.

Any help would be greatly apprecaited, thank you!

P.S. I'm using Eric Meyer's CSS reset.

Red line marks the bottom edge of the flex container pronouncing the discrapancy of the container's height with the height of its children

<div class="flex">
    <div class="flex-item">
        <img src="./img/img01.jpg" alt="Image">
    </div>
    <div class="flex-item">
        <img src="./img/img02.jpg" alt="Image">
    </div>
    <div class="flex-item">
        <img src="./img/img03.jpg" alt="Image">
    </div>
    <div class="flex-item">
        <img src="./img/img04.jpg" alt="Image">
    </div>
</div>
.flex {
    display: flex;
    column-gap: 1em;
}

.flex-item {
    flex: 1;
    overflow: hidden;
}

.flex-item > img {
    max-width: 100%;
    transform: scale(1);
    transition: all 0.2s ease-in-out;
}

.flex-item:hover > img {
    transform: scale(1.125);
}

CodePudding user response:

All what you need, just put to the .flex-item class display: flex.

.flex-item {
  display: flex; /* new line */
  flex: 1;
  overflow: hidden;
}

  • Related