Img's max-height not respecting parent's dimensions

后端 未结 5 855
面向向阳花
面向向阳花 2020-12-04 01:33

I have an img element inside a liquid div. That img has its max-height set to 100%. So, if the image is taller than the div, it should

相关标签:
5条回答
  • 2020-12-04 01:49

    I bumped into this as well and I managed to get a consistent height across different browsers using vh units in CSS, for example max-height: 5vh; as in 5% of the viewport height.

    0 讨论(0)
  • 2020-12-04 01:55

    If you still want the container to be % based and not px, you can make the container display: flex, and the image

    object-fit: contain;
    max-width: 100%;
    
    0 讨论(0)
  • 2020-12-04 01:57

    I figured it out. For an element's max-height to work, one of its parents must have a height attribute defined (apparently in a fixed unit, like px, not in percentage).

    From the w3c specs:

    The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the percentage value is treated as '0' (for 'min-height') or 'none' (for 'max-height').

    Since none of my img's parent have a fixed height defined, I had to limit my img to max-width instead.

    Edit: Also, it seems webkit takes the specs a little too literally: https://stackoverflow.com/a/3808701/857807

    I used the workaround presented in that thread, and used position: absolute; max-height: 100%; top: 0.

    0 讨论(0)
  • 2020-12-04 02:04

    According to @dcastro answers ( with I full agree ) Any parent element must have an fixed value ( like in px ) instead a relative value (like % ) . So, a little trick using Jquery that allows to use only relative value

    <div id="E_slick" style="height: 75%">
        <img class="eve_img" src="myfile.jpg" style="max-width: 100%; max-height:100%"> 
    </div>
    

    So, the trick is to get the hood height and set it to img, to make it easier, lets use jQuery:

    $('.eve_img').height( $("#E_slick").height() )
    
    0 讨论(0)
  • 2020-12-04 02:13

    Try adding the width and height attributes to your img's

    Also set the natural dimensions in your HTML to help the browser render.

    HTML

    <img src="img/mywine/2high.png" width="123px" height="123px"> 
    

    CSS

      img{
           max-width: 100%
           height: auto;
        }
    
    0 讨论(0)
提交回复
热议问题