Set the height of a div to be half of whatever the width is

社会主义新天地 提交于 2019-12-03 02:01:49

If you're ok with supporting only modern browsers, you can do this: http://jsfiddle.net/kNPfh/

The vw measure is in 1/100th of the viewport width, so 50vw is 50% of screen width.

<div class='halfwidth'></div>

.halfwidth {
    width: 100%;
    height: 50vw;
    background-color: #e0e0e0;
}

if not, you can use: http://jsfiddle.net/ff7WC/

$(window).on( 'resize', function () {
    $('.halfwidth').height( $(this).width() / 2 );
}).resize();

Make sure you have a js file then use this

$(window).load(function(){
    $('.element').height($('.element').width() / 2);
    $(window).resize(function(){
        $('.element').height($('.element').width() / 2);
    });
});

http://jsfiddle.net/Hive7/8CNtU/2/

You can do it with the help of padding on a parent item, because relative padding (even height-wise) is based on the width of the element.

CSS:

.imageContainer {
    position: relative;
    width: 25%;
    padding-bottom: 25%;
    float: left;
    height: 0;
}

img {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
}

For details, see this article on the subject http://wemadeyoulook.at/how-we-think-about/proportional-scaling-responsive-boxes

You can also use jquery for that, something like:

$('.ss').css('height',width()/2);

Please choose this as the correct answer if it solves your doubt by clicking on the tick symbol to the left.

Michael Walter

This is not possible with pure CSS. You have to use jQuery for it to generetate the new sizes. I've found this in SO: Using jQuery To Get Size of Viewport

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!