CSS Media Queries instead of JavaScript code

Using CSS Media Queries instead of JavaScript or JQuery code

Before CSS3 coming out, if you needed to change the layout programatically when window size is changed you would have to write a small JavaScript or JQuery to handle window resize event and perform some action on the DOM to addapt your layout.

In case you would use JQuery (which is most of the cases as I do not remember last time I wrotw plain JavaScript code) you would have to hook to window resize event and handle every resize. Based on your condition you would apply some CSS to specific element or strip style from it.

Sample JQuery code for something like this would be

$(window).resize(function(){
	var self=$(this);
	var container = $(".container");
	if((self).width() <= 300){
		$(container).css("background-color", "lightblue");
	}
	else{
		$(container).css("background-color","");
	}
});
    

Code above will change the background color if window size comes down to 300px or less. Equivalent code for this in CSS3 using media queries would be

@media screen and (max-width: 300px) {
    .container {
        background-color: lightblue;
    }
}
    

You can see that the code is more becoming designer thing than front-end developer thing which is I think good as designer and developer work is now more separated and roles on a project can be much easily defined.

In case you want to do the opposite thing than in previous media query and apply CSS rule for screen sizes greater than 300px code would be the following

@media screen and (min-width: 300px) {
    .container {
        background-color: darkblue;
    }
}
    

This way you can create different CSS layout rules for desktop, tablet and smartphone.

Unfortunately media queries are not supported by all browsers. Complete list of CSS media queries can be found at http://caniuse.com/#feat=css-mediaqueries.

Another disadvantage for media queries is that it does not support more complex queries. For more complex selector queries you would have to use LESS or SASS libraries.

References

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.


About the author

DEJAN STOJANOVIC

Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform including ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

.NET

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article