Ryan Hall
Ryan Hall

Reputation: 13

Stretch div to browser height using css in jquery

I am trying to stretch a div to browser height using css in jquery. but it seems not working. I am able to apply the 100% width to the div and it works. Not the height though. any reason why? Thanks!

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<script>
	
$(function() {
    $('.test').css({
       "background-color": "yellow",
"width": "50%",
"height": "50%",
    });
	
});
</script>

<div class="test" style="width: 15px; height: 60px; background-color: red"><div>

Upvotes: 1

Views: 63

Answers (3)

Danny van Holten
Danny van Holten

Reputation: 932

Use 100vh. Which means viewport height. The reason why 100% doesn't work is because the element takes the height of the parent. Not your window / viewport.

Blocked elements automatically get 100% width. But with the height of an element this is not the case. So everything from the html to your element should be set to 100%. Either that, or you should just use 100vh.

Upvotes: 1

Fizzix
Fizzix

Reputation: 24375

If you must do this with jQUery, use $(window).width() and $(window).height() to get the browser dimentions.

Like so:

$(document).ready(function() {
  $('.test').css({
    "background-color": "yellow",
    "width": $(window).width(),
    "height": $(window).height(),
  });
});

Click here for a working demo.


If you do not need to do this programmically, I highly recommend using the following CSS solution:

.test {
  background-color: yellow;
  width: 100vw;
  height: 100vh;
}

vw and vh stand for Viewport Width and Viewport Height.

You could even turn the above into a CSS class, and then use jQuery to simply apply that class using jQuery's addClass() function. Here is another demo using that solution.

Upvotes: 1

MartinWebb
MartinWebb

Reputation: 2008

This is because you would need to apply the 100% to the body and the html since they are surrounding your div and forcing it to their height. You can also use 100vh for 100% of the viewport height.

<html>
 <body>
  <div class="test" style="width: 15px; height: 60px; background-color: red">    <div>
 </body>
</html>

CSS

html,body {
height:100%;
min-height: 100%;
}

You can also use 100vh rather than 100% which means viewport (100%).

see: https://snook.ca/archives/html_and_css/vm-vh-units

Upvotes: 1

Related Questions