简体   繁体   中英

Dynamically adjust image width & height using css

I have a photo gallery page displaying images of varying widths and heights. I'm trying to use CSS to dynamically display all images in a uniform width and height.

I currently have everything working except the dynamic height. I have image height set manually and then adjusting at different breakpoints. I'm using @media page widths to trigger different image heights. I'm fine with the excess height being trimmed off (hidden).

@media(max-width: 1300px)
    {
    ul.grid-nav li {
    display: block;
    margin: 0 0 5px;
    }
    ul.grid-nav li a {
    display: block;
    }
    ul.rig {
    margin-left: 0;
    }
    ul.rig li {
    width: 45% !important; /* over-ride all li styles */

    }

    .img { 

    height: 250px; 
    overflow: hidden; 
    }
}

Example Page http://foothillertech.com/student/webdesign/2015/2nd/02_50/classwork/cssPhotoAlbum/dev/index_cssPhoto.html

Does anyone know of a way to dynamically set the .img height based on the rig.li width?

Thanks!

There is a trick involving relative/absolute positioning and padding. You specify padding-bottom as a percentage of the width of the image.

For 16:9 images, use this css.

ul.rig li .img {
    overflow: hidden;
    position: relative;
    padding-bottom: 56.25%;
    height: 0;
}

ul.rig li img {
    max-width: 100%;
    position: absolute;
}

Try following jquery

$(document).ready(function () { 
    $(".img").css("width", $('ul.rig li').width());
    $(".img").css("height", $('ul.rig li').height());
});

Hope this will help you.

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