简体   繁体   中英

Set width of a div in respect to height

I have a div #slideshow with images of 2:1 aspect ratio. So, set height of image I am using jQuery:

Note: The Slideshow Div is 100% wide with respect to browser window. If user makes the browser window, smaller - it is going to be smaller.

slideWidth();

function slideWidth(){
var width = $("#slideshow").css("width");
var height = (parseInt(width.substr(0,width.length-2)) /3);
$("#slideshow").css("height",height+"px");
}

And, to make the width change dynamically, I use setTimeout:

setInterval(slideWidth,1000);

This is actually working as I want. But I think I am heavily giving high impact on the website by refreshing the function slidewidth every second.

Is this achievable through CSS3? Or with jQuery/JS with less Website Impact?

Thank you. Feel free to comment with new ways/ideas.

There's a css-only approach using pseudo elements and padding:

div {
    width: 100%;
    position: relative;
    background: red;
}

div:before {
    display: block;
    content: "";
    padding-top: 50%;
}

The combination of the pseudo padding-top can be used to vary between aspect ratios.

In this case, the 50% padding is equivalent to aspect ratio of 2:1

Working Fiddle Example

You should be using jquerys .resize(); This adds an event listener waiting for the container to resize. Ej:

$(window).resize(function(){
  //do your logic here
});

Jquery resize

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