p09687
p09687

Reputation: 33

How to zoom into image while keeping dimensions the same in CSS

I know that when you use overflow:hidden on the div wrapping the image, the dimensions will stay the same. But I am not sure how to do this with flex items. I tried adding a div to the outside of each image but it didn't work so I reverted back to my original code

Here's my code:

<section id="related">
    <h1>Related Titles</h1>
    <div class="related">
        <img src="images/spiderverse.jpg" alt ="Into The Spiderverse">
        <img src="images/incredibles.jpg" alt ="The Incredible 2">
        <img src="images/megamind.jpg" alt ="Megamind">
    </div>
</section>

.related {
    display:flex;
    grid-column: 1/3;
    grid-row:5/6;

}

.related>img {
    width:65%;
    margin:10px;
}

#related>h1 {
    font-size: 30px;
    padding-bottom:20px;
}

.related>img:hover{
    transform:scale(1.2);
    transition:.2s ease;
}

Upvotes: 0

Views: 2058

Answers (1)

Jax-p
Jax-p

Reputation: 8531

If you wrap each img in div (or any other element) with overflow:hidden and set img some width and height or (min-height...) it works well.

I am not sure why do you use width: 65% on each image but if you want to fill whole row you can use flex-grow: 1.

Also you don't have to use grid-column and grid-row attribute aslong as you use flex not grid.

.related {
    display: flex;
}
.related > div {
    margin: 10px;
    overflow: hidden;
    flex-grow: 1;
}
.related-img {
    width: 100%;
    height: 100%;
    will-change: transform;
    transition: transform .2s ease;
}
.related-img:hover{
    transform: scale(2);
}
<div class="related">
   <div><img class="related-img" src="https://via.placeholder.com/150" alt ="Into The Spiderverse"></div>
   <div><img class="related-img" src="https://via.placeholder.com/150" alt ="The Incredible 2"></div>
   <div><img class="related-img" src="https://via.placeholder.com/150" alt ="Megamind"></div>
</div>

As you can see I've changed transition: .2s to transition: transform .2s to target explicit attribute and inserted will-change attribute which hints browsers how an element is expected to change.

Upvotes: 2

Related Questions