Limit the height of a responsive image with css

前端 未结 3 795
粉色の甜心
粉色の甜心 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/

提交回复
热议问题