Home > Net >  Responsive image container (with max-width and max-height defined) svg icon inside the container
Responsive image container (with max-width and max-height defined) svg icon inside the container

Time:09-06

I have an image container (.section-first-video) that should be responsive with min-height: 187px min-width: 328px and max-height: 240px max-width: 420px. There is also a 'play' icon inside the div that should be placed in the center and should not change its size.

Here is the DEMO: https://github.com/meri-maki/stackoverflow-demo-ingrad https://meri-maki.github.io/stackoverflow-demo-ingrad/

The main issue that I currently have is that max-height: 240px doesn't work and the container keeps getting larger in height.. There should be a workaround but i can't think of anything..

HTML

<section>
        <div >
                    <img src="./resources/youtube-cover.png" alt="youtube-cover">
                    <img  src="./resources/icon-play.svg" alt="play icon">
                </div>
    </section>
            </section>

CSS

section {
    display: grid;
    grid-template-columns: repeat(12, [col-start] 1fr);
    column-gap: 20px;
    align-items: start;
    margin: 5% 4.4444%;
}
.section-first-video {
    position: relative;
    border-radius: 2rem;
    margin-bottom: 2rem;
    grid-column: col-start 1 / span 12;
    max-height: 240px;
    max-width: 420px;
    min-width: none;
    padding-bottom: 57%;
    overflow: hidden;
}
.section-first-video img{
    width: 100%;
    height: 100%;
    object-fit: cover;
    object-position: center;
    position: absolute;
}
.section-first-video img.play-icon{
    object-fit: none;
}

CodePudding user response:

You are using padding-bottom: 57%; to control the "aspect-ratio" of the .section-first-video box, which will ignore the min/max properties you have set up.

Most browsers now support aspect-ratio these days to actually set the container aspect ratio you want, which doesn't require the padding trick, but will follow the min/max values you set. In this case, you would set your widths, and then set the aspect-ratio property to what you'd like for a height.

section {
    display: grid;
    grid-template-columns: repeat(12, [col-start] 1fr);
    column-gap: 20px;
    align-items: start;
    margin: 5% 4.4444%;
}
.section-first-video {
    position: relative;
    border-radius: 2rem;
    margin-bottom: 2rem;
    grid-column: col-start 1 / span 12;
    overflow: hidden;
    min-width: 328px;
    max-width: 420px;
    height: auto;
    aspect-ratio: 16/9;
}
.section-first-video img{
    width: 100%;
    height: 100%;
    object-fit: cover;
    object-position: center;
    position: absolute;
}
.section-first-video img.play-icon{
    object-fit: none;
}

Link to JSFilddle - https://jsfiddle.net/uf0tq2e4/1/

  • Related