Pavlo B. Pavlo B. - 2 months ago 6
CSS Question

Responsive height of a div using jquery .css

Hello guys this is my first question here and it's about how to make my div with a responsive height usiing jquery.

This is the funcion I've used to try it:

$(document).ready(function(){
$(".panel").css("height: $('window').height();"); });


But when I save and I try to run my page I can't see anything because the height of the div is set to 0 I don't even know if this is the correrct way to do it...

Please help me with that and thanks for all.

Answer

If you want the jQuery way, you can do it like following:

 $('.panel').css('height', $(window).height()); 
 $(window).resize(function() {      
    $('.panel').css('height', $(window).height()); 
  });   

Check the following snippet example:

$(".panel").css("height", $(window).height());
$(window).resize(function() {
  $(".panel").css("height", $(window).height());
});
body {
  background-color: yellow;
  padding: 0;
  margin: 0;
}
.panel {
  background-color: blue;
  width: 100px;
}
<div class="panel">
  This is the panel
</div>

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

Also you can do it with one line of CSS, using height:100vh;
Check the browser support for vh units, Can I use vh

body {
  background-color: yellow;
  padding: 0;
  margin: 0;
}
.panel {
  background-color: blue;
  height: 100vh;
  width: 100px;
}
<div class="panel">
  This is the panel
</div>