Limit the height of a responsive image with css

前端 未结 3 794
粉色の甜心
粉色の甜心 2021-01-31 02:01

My end goal is to have a fluid that won\'t expand past an explicitly set height of a parent/grandparent element using only css.

Currently I\'m

相关标签:
3条回答
  • 2021-01-31 02:20

    The trick is to add both max-height: 100%; and max-width: 100%; to .container img. Example CSS:

    .container {
      width: 300px;
      border: dashed blue 1px;
    }
    
    .container img {
      max-height: 100%;
      max-width: 100%;
    }
    

    In this way, you can vary the specified width of .container in whatever way you want (200px or 10% for example), and the image will be no larger than its natural dimensions. (You could specify pixels instead of 100% if you didn't want to rely on the natural size of the image.)

    Here's the whole fiddle: http://jsfiddle.net/KatieK/Su28P/1/

    0 讨论(0)
  • 2021-01-31 02:24

    I set the below 3 styles to my img tag

    max-height: 500px;
    height: 70%;
    width: auto;
    

    What it does that for desktop screen img doesn't grow beyond 500px but for small mobile screens, it will shrink to 70% of the outer container. Works like a charm.

    It also works width property.

    0 讨论(0)
  • 2021-01-31 02:40

    You can use inline styling to limit the height:

    <img src="" class="img-responsive" alt="" style="max-height: 400px;">
    
    0 讨论(0)
提交回复
热议问题