Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a CSS file with Javascript and dynamically alter the page

So CSS @media queries don't work in IE8.

@media (min-width: 768px) {
/* some css */
}
@media (min-width: 972px) and (max-width: 1024px){
/* different css */
}

Now, I could create separate CSS files named IE_min768.css and IE_min972_max1024 and use Javascript to dynamically load and unload the files as the page width is adjusted. But that violates D.R.Y. and would be a pain to maintain CSS in multiple places.

Would it be possible to use Javascript (in IE only) to actually read the CSS file, detect the @media sections and dynamically apply that CSS to the browser in the correct situation?

like image 920
brentonstrine Avatar asked Sep 06 '12 19:09

brentonstrine


People also ask

Can we change CSS file dynamically?

If you want to change the CSS styles dynamically you'll have to attach this portion of code to some event. For example, if you want to change the styles of your element when clicking on a button, then you have to first listen to the click event and attach a function containing the previous code.

Can JavaScript modify the CSS file?

JavaScript can interact with stylesheets, allowing you to write programs that change a document's style dynamically. There are three ways to do this: By working with the document's list of stylesheets—for example: adding, removing or modifying a stylesheet.

Can JavaScript read CSS?

The CSS file is used to describe how HTML elements will be displayed. There are various ways to add CSS file in the HTML document. JavaScript can also be used to load a CSS file in the HTML document.


1 Answers

Don't re-invent the wheel. Just use respond.js.

From the readme on GitHub:

The goal of this script is to provide a fast and lightweight (3kb minified / 1kb gzipped) script to enable responsive web designs in browsers that don't support CSS3 Media Queries - in particular, Internet Explorer 8 and under. It's written in such a way that it will probably patch support for other non-supporting browsers as well (more information on that soon).

like image 154
Joseph Silber Avatar answered Oct 31 '22 22:10

Joseph Silber