JQuery to set dynamic maximum width

I am not very good at jQuery, so an ideal code solution would be perfect.

The function will be:

  • Get a browser screen width of 70%.
  • Convert this width to the corresponding px value
  • Set the maximum width of #mainContainer using the value obtained from the conversion / calculation.

Here is the CSS style for the container that I want to set max-width with:

 #mainContainer { background-image: url(bg3.jpg); background-repeat: repeat; background-color: #999; width: 70%; padding: 0; min-width: 940px; /* 940px absolute value of 70%. */ margin: 0 auto; min-height: 100%; /* Serves as a divider from content to the main container */ -webkit-border-radius: 10px; border-radius: 10px; } 
+7
source share
2 answers

You should be able to copy it inside the <script> tag anywhere on the page where you have jQuery, and it should work.

 $( document ).ready( function(){ setMaxWidth(); $( window ).bind( "resize", setMaxWidth ); //Remove this if it not needed. It will react when window changes size. function setMaxWidth() { $( "#mainContainer" ).css( "maxWidth", ( $( window ).width() * 0.7 | 0 ) + "px" ); } }); 
+26
source

Or define a function for the window.onresize event

 window.onresize = function() { var newWidth = ($(window).width() * .7); $("#mainContainer").css({ "maxWidth": newWidth }); } 
 #mainContainer { background-color: #999; width: 70%; padding: 0; min-width: 30px; /* 940px absolute value of 70%. */ margin: 0 auto; min-height: 100%; /* Serves as a divider from content to the main container */ -webkit-border-radius: 10px; border-radius: 10px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="mainContainer">-</div> 
+2
source

All Articles