Object-fit and scaling images within an overflow container


by Jeremy Caudle
code

I'm still not used to using object-fit, so I wanted to play around with it a bit. I made use of it in this post along with transitions to try and recreate this effect I've seen on a number of sites. I'm not sure if this cannot be done with a background image as well, but I took a shot at it using just an img and overflow:hidden set on the wrapping picture element. Something feels wrong about applying the overflow to the picture element, so I probably wouldn't use this same technique on a live site

Object-Fit Test

View the code:

HTML and JS
<section class="code-block">
            <div class="card">
                <picture>
                    <img src="https://jeremycaudle.com/floorshotJC.jpeg" width="300" height="300" />
                </picture>
                <footer><p>Object-Fit Test</p></footer>
            </div>
        </section>
CSS
section.code-block {
                margin: 3rem auto;
                background-color:darkgray;
                padding: 1rem;
            }

            .card {
                width: 300px;
                padding: .5rem;
                border-radius: 1rem;
                margin: 2rem auto;
                position: relative;
                background: linear-gradient(rgb(27, 27, 61), rgb(26, 70, 26));
                transition: box-shadow .5s ease-out, linear-gradient .5s ease-in-out;
            }

            .card:hover {
                box-shadow: 5px 5px 5px 5px rgba(0, 0, 0, 0.125);
                background: linear-gradient(rgb(37, 37, 83), rgb(34, 90, 34));
            }

            .card header, .card footer { background-color: white;}
            .card picture {
                display: block;
                max-width: 300px;
                overflow: hidden;
                border-radius: .75rem .75rem 0 0;
            }
            .card img { 
                display: block;
                object-fit: cover;
                transition: transform .5s ease-out;
                margin: 0;
                }
            .card img:hover{ transform: scale(1.05); }
            .card footer {
                min-height: 1rem;
                padding: 1rem;
                border-radius: 0 0 .75rem .75rem;
            }
            .card p {
                text-align: center;
                font-family: Helvetica, Arial, sans-serif;
                font-weight: 600;
                margin: 0;
            }