Jquery dynamically resizes div to always be the width of the browser

  • 2020-03-30 03:13:14
  • OfStack

Sometimes we need to set the width of the div to be the width of the browser. Of course, we can do this in a relative layout, but we can also do it with jquery.
 
<!doctype html> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>jquery test</title> 
<script src="jquery-1.11.1.min.js"></script> 
<style type="text/css"> 
.show 
{ 
width: 500px; 
height: 50px; 
background-color: red; 
} 
</style> 
</head> 

<body> 
<div class="show"></div> 
<script> 
var browser_width = $(document.body).width(); 
$("div.show").css("width",browser_width); 
$(window).resize(function() { 
browser_width = $(document.body).width(); 
$("div.show").css("width",browser_width); 
}); 
</script> 
</html> 

We use $(document.body).width() to get the width of the browser content. When the page loads, we initialize the width of the div to be the width of the browser page.

Related articles: