Search code examples
cssgridcss-grid

How to stretch image in flipping card on a grid


I am trying to create a flipping card in a css grid. Unfortunately the background picture's behaviour is different from what I would expect. The image is supposed to stretch to the size of the card. Always keeping the same width/height ratio.

Please check out my example on fiddle: https://jsfiddle.net/x4ymfor6/

<div class="grid">
    <div class="card">
        <div class="card-inner">
            <div class="front"><div class="placeholder">front</div></div>
            <div class="back">back</div>
        </div>
    </div>
</div>

    .card {
        background-color: transparent;
        max-width: 100%;
        max-height: 100%;
        perspective: 1000px;
    }

    .card-inner {
        width: 100%;
        height: 100%;
        text-align: center;
        transition: transform 0.8s;
        transform-style: preserve-3d;
    }

    .card:hover .card-inner {
        transform: rotateY(180deg);
    }

    .front, .back {
        display: grid;
        grid-template-columns: repeat(1, 1fr);
        position: absolute;
        width: 100%;
        height: 100%;
        backface-visibility: hidden;
    }

    .front {
        background-color: #bbb;
        color: black;
    }

    .back {
        background-color: dodgerblue;
        color: white;
        transform: rotateY(180deg);
    }

    .grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        grid-gap: 1em;
        grid-auto-rows: minmax(170px, auto);
        margin: 5em;
    }

    .grid > div {
        background-repeat: no-repeat;
        background-position: center center;
        background-size: 90%;
    }

    .grid > div {
        background-color: #221e1e;
        border-radius: 3px;
        box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.99);
    }

    .card-image {
        max-width: 100%;
        max-height: 100%;
    }

    .placeholder {
        background-image: url(https://svgshare.com/i/EMw.svg);
        max-width: 100%;
        max-height: 100%;
        background-repeat: no-repeat;
        background-position: center center;
    }

Solution

  • You can use the background-size property and set it to contain.

    Like this :

        .placeholder {
            background-image: url(https://svgshare.com/i/EMw.svg);
            background-size: contain;
            max-width: 100%;
            max-height: 100%;
            background-repeat: no-repeat;
            background-position: center center;
        }