How to Dynamically Adjust CSS Stylesheet Based on Browser Width

How to dynamically change css styling for a div according to browser screen size

Try reading about and using media queries.

Your code should be something like:

.main {
margin-left: 500px;
}

/* For mobile screens */
@media screen and (max-width: 480px) {
.main {
margin-left: 0;
}
}

Dynamically adjusting css variables in a style sheet?

You can keep user color or theme setting in options table and generate css file based on it. If configuration options are not too big consider dynamically putting it in file itself as inline css. It will override rules from external css.

If theme has predefined color schemes, separate theme rules in css files and place it as alternate stylesheets in html. Switch stylesheets files based on users color selection, using js.

What's the cleanest way to set dynamic style elements?

Using JavaScript is one option. As an alternative I'll offer 2 CSS-only solutions. There are 2 solutions that come to mind first.

Option #1

The first is pretty standard - set the height and width to 100%. The caveat here is every parent parent container needs it's height and width set to 100% too. Like this:

html,body {  margin: 0;  padding: 0;  width: 100%;  height: 100%;}
main { width: 100%; height: 100%;}
#gameCanvas { background-color: red; width: 100%; height: 100%;}
<main>  <div id="gameCanvas"></div></main>

How to use particular CSS styles based on screen size / device

Use @media queries. They serve this exact purpose. Here's an example how they work:

@media (max-width: 800px) {
/* CSS that should be displayed if width is equal to or less than 800px goes here */
}

This would work only on devices whose width is equal to or less than 800px.

Read up more about media queries on the Mozilla Developer Network.

Change CSS class if window is less than ()

You could try :

(function($) {

var $sides = $('.side');

var setCss = function() {
if($(window).height() > 600) {
$sides.css('width', 400).css('height', 700);
} else {
$sides.css('width', 300).css('height', 550);
}
};

$(document).ready(function() {
setCss();
$(window).resize(setCss);
);

})(jQuery);

How to set element style depending on the window.innerWidth

With class name you will get a collection of elements not an element, so you must change this:

getElementByClassName

to this:

getElementsByClassName

And you need to affect elemets in your collection collection:

var elements = document.getElementsByClassName('2');
for(var i = 0; i < elements.length; i++)
{
elements[i].setAttribute("style","clear: right;");
}

And with media query:

@media only screen and (max-width: 600px) {
.2{
width: 25%;
float: left;
}
}

And please remember that "2" is not a true class name and you need to change it to some thing like "div2"



Related Topics



Leave a reply



Submit