简体   繁体   中英

Set height of div in pixels based off width of browser window in % (jQuery or JS?)

I am trying to set up a black border around a webpage. For the left and right side, just making "width: 5%;" in the CSS is fine. But then I want JS/jQuery to work out how many pixels that is, and make that the height of the top and bottom div.

Is this possible?

Thanks.

This should work for you

var val = $(".leftAndRight").width();
$(".topAndBottom").height(val);

Or with one line:

$(".topAndBottom").height($(".leftAndRight").width());

You can determine the value for the border width programmatically, assign it to all four borders, and also refresh it any time you resize:

var width,
    drawBorder = function () {
        var body = $('body'),
            width = body.width() * 0.05;
        body.css('border-width', width + 'px');
    };

drawBorder();

$(window).resize(function () {
    drawBorder();
});

Demo

If you set the left and right width in your stylesheet and then use JS to give the same border width to the top and bottom, unless you use a resize function your left and right borders will change every time you resize but your top and bottom borders will remain fixed.

You can use .width() to find width without the border and .outerWidth to find the width including the border. I think .outerWidth also gives you the width with the padding you may have to subtract that.

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