Jonah
Jonah

Reputation: 1545

Setting an element's height to the height available in the viewport?

My element's height increases depending on what the user does with it. If I give it a wrapper div, and give that div an explicit pixel height and overflow:auto, it works as I would want it to (when the element becomes bigger than the height of its parent, it doesn't increase the size of the parent). I want the wrapper div to be as big as the space available on the page, but not allow it to expand beyond that. Giving it height:100% doesn't work, it just gets bigger. Giving it height:100vh also doesn't work because there are other elements on the page and so the size is too big.

I want the wrapper div to be able to expand until it becomes too big for the viewport (which height:100vh would achieve if it were not for the other elements on the page).

Basically I'm looking for something like height : amount of available space in the viewport.

Upvotes: 1

Views: 885

Answers (3)

Vinod Bhavnani
Vinod Bhavnani

Reputation: 2225

function resizeElement() {
var height = $(window).height();
var neededHeight = (70 * height) / 100; //If you want 70% of the viewport
neededHeight = parseInt(neededHeight) + 'px';
$("div").css('height',neededHeight);
}
$(document).ready(function() {
resizeElement();
$(window).bind('resize', resizeElement);
});

You can try this. You may need to check what value do you get in var height. Depending on that you can append px or not in neededHeight. This is basically the logic.

Upvotes: 0

Jonah
Jonah

Reputation: 1545

This is what I ended up doing:

var viewportHeight = $(window).height();
var offset = $('#gridWrapper').offset().top;
$('#gridWrapper').height(viewportHeight - offset);

I execute the same stuff again on resize. gridWrapper is the id of the wrapping div.

Upvotes: 1

usman khan
usman khan

Reputation: 139

you can use height:80vh or similar depends on the height of your other elements

Upvotes: 0

Related Questions