简体   繁体   中英

Change parent div height according to child img height, without exceeding parent divs max-width

I have yet to find any good CSS code that solves my problem, and that works in all major browsers. That being said, safari automatically does this whenever I use max-height: 90% in the parent div, and sets max-height: 100% in the child img. However, Mozilla does not.

Is there any cross browser solution for making sure the img does not expand more than the height of the parent div. But the parent div can adjust to the childs height, and be limited to its own max-height ?

I also accept jQuery, but prefer CSS in the answer.

When it comes to width this will always be width: 60% in the parent div, and max-width: 100% in the child img.

Code

.fullScaleContent{
    position: fixed;
    width: 60%;
    max-height: 90%;
    height: auto;
    margin: 2% auto;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -55%);
    -webkit-transform: translate(-50%, -55%); 
    -ms-transform: translate (-50%, -55%);
}
.fullScaleContent img{
    width:auto;
    height:auto;
    max-width: 100%;
    max-height: 100%;
}

Image examples: First image is height limit in safari, second is in Firefox. I need both to be similar to safari. PS: Black border is the actual border of the div

高度限制 - safari

限制高度 - Firefox

Limited width - works fine in both - height is adjusted according to img, with max width 60%

有限的宽度 - 两者

Used object-fit: contain

If you use position , use it on your image to so it's in the flow.

Review Snippet in full page and resize it.

SNIPPET

 *, *:before, *:after { box-sizing: border-box; } html, body { width: 100%; height: 100%; position: relative; } .fullScaleContent { position: fixed; width: 60%; max-height: 90%; height: auto; margin: 2% auto; left: 50%; top: 50%; transform: translate(-50%, -55%); -webkit-transform: translate(-50%, -55%); -ms-transform: translate (-50%, -55%); } .fullScaleContent img { position: relative; object-fit: contain; min-width: 128px; max-width: 100%; height: auto; }
 <figure class="fullScaleContent"> <img src="https://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png"> </figure>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM