Make responsive image fit parent container

前端 未结 4 1550
抹茶落季
抹茶落季 2020-12-17 02:29

I\'ve been trying to figure out if there is a pure CSS solution to ensure the image within my banner doesn\'t go below the height of the parent but keep ratio of the image.<

相关标签:
4条回答
  • 2020-12-17 02:45

    Instead of using an < img > tag, I made that image the background-image for a div and gave it the following styles:

    .banner_holderImage{
        height: 100%;
        position:relative;
        background:   url("http://placekitten.com/g/800/600")no-repeat;
        background-size: cover;
        background-position: center;
    }
    

    here's the fiddle I was using: http://jsfiddle.net/MathiasaurusRex/LkxYU/4/

    Here's the complete HTML and CSS:

    <div class="banner_holder">
        <div class="banner_holderImage"></div>  
    </div>
    

    --

    .banner_holder{
        width: 100%;
        height: 300px;
        min-height: 200px;
        position: relative;
        outline:1px dotted red;
    }
    
    .banner_holderImage{
        height: 100%;
        position:relative;
        background:   url("http://placekitten.com/g/800/600")no-repeat;
        background-size: cover;
        background-position: center;
    }
    
    0 讨论(0)
  • 2020-12-17 02:49

    try:

    .banner_holder img{
    height: 100%;
    /* OR */
    height: inherit;
    }
    
    0 讨论(0)
  • 2020-12-17 02:51

    Your image will inevitably be out of ratio depending on the screen size, why not try a background image:

    .banner_holder{
      width: 100%;
      height: 300px;
      min-height: 200px;
      position: relative;
      outline:1px dotted red;
      background: url('http://placekitten.com/g/800/600') center no-repeat;
      background-size: cover;
    }
    

    or you could just add a max height to your image tag:

    .banner_holder img{
      width: 100%;
      max-height: 300px;
    }
    
    0 讨论(0)
  • 2020-12-17 02:54

    Use max-height and max-width to be sure that image will always fit the parent div:

    .banner_holder{
        width: 200px;
        height: 300px;
        position: relative;
        outline:1px dotted red;
    }
    
    .banner_holder img{
        max-width: 100%;
        max-height: 100%;
    }
    

    EDIT: Sorry, I miss the part where you wrote about 300px cut-off stuff :) MathiasaurusRex's answer is correct.

    0 讨论(0)
提交回复
热议问题