SASS 3.2 Media Queries and Internet Explorer Support - css

I recently implemented this technique with SASS 3.2 using #content blocks on a project I've been working on, and I've just gotten to the point where I need to include support for older browsers such as IE7 and 8.
Example:
.overview {
padding: 0 0 19px;
#include respond-to(medium-screens) {
padding-top: 19px;
} //medium-screens
#include respond-to(wide-screens) {
padding-top: 19px;
} //medium-screens
}
They both don't support media queries, and I've often handled this in the past by serving up all styles to these browsers when I had my media queries separated into separate partial files such as _320.scss, _480.scss and in my IE stylesheet loading them like so:
#import 320.scss;
#import 480.scss;
etc.
Which would load all styles, and always assign IE7 - 8 a 940px (or whatever the max width is) layout and styles. By nesting styles in SASS 3.2 inline like this, it eliminates the need for separate partial stylesheets, but totally screws up how I load styles for IE.
Any ideas or solutions on how to combat this? I could use a polyfill such as respond.js to force IE to use media queries, but would prefer to just serve up a non-flexible site to IE.
Any ideas on either how to best organize these files, or a better solution?

You can generate a separate stylesheet for IE<9 that contains everything your normal sheet has, but with flattened media queries based on a set width.
Full explanation here http://jakearchibald.github.com/sass-ie/, but basically you have this mixin:
$fix-mqs: false !default;
#mixin respond-min($width) {
// If we're outputting for a fixed media query set...
#if $fix-mqs {
// ...and if we should apply these rules...
#if $fix-mqs >= $width {
// ...output the content the user gave us.
#content;
}
}
#else {
// Otherwise, output it using a regular media query
#media screen and (min-width: $width) {
#content;
}
}
}
Which you'd use like this:
#include respond-min(45em) {
float: left;
width: 70%;
}
This would be inside all.scss, which would compile down to all.css with media queries. However, you'd also have an additional file, all-old-ie.scss:
$fix-mqs: 65em;
#import 'all';
That simply imports all, but flattens media query blocks given a fake width of 65em.

I use LESS for a lot of my work, but on larger projects, with many people working across files, I don't like using breakpoint files, such as 1024.less.
My and my team use a modular approach, such as header.less which contains all the code for just the header, including the associated breakpoints.
To get round IE problems (we work in a corporate environment), I use this approach:
#media screen\9, screen and (min-width: 40em) {
/* Media queries here */
}
The code inside the media query is always executed by IE7 and less. IE9 and above obeys the media queries like a proper browser should. The problem is IE8. To solve this, you need to make it behave like IE7
X-UA-Compatible "IE=7,IE=9,IE=edge"
I've found this doesn't always work if set in the metatags in the HTML, so set it using the server headers.
See the gist here:
https://gist.github.com/thefella/9888963
Making IE8 act like IE7 isn't a solution that works for everyone, but it suits my needs.

Jake Archibald has the best technique I've seen to date for achieving this. This technique automatically creates a separate stylesheet for IE, with all the same styles inside of your media queries but without the media query itself.
I also campaigned to get this technique built into the popular breakpoint extension for Sass, if you're interested in using that!

If you wanted to keep everything under one roof and only have a single http request for your older browser visitors you could do something like this
Setting up your initial respondto mixin
// initial variables set-up
$doc-font-size: 16;
$doc-line-height: 24;
// media query mixin (min-width only)
#mixin breakpoint($point) {
#media (min-width: $point / $doc-font-size +em) { #content; }
}
this will create a min-width media query and output your px value ($point) as an em value.
From this you'd need to create this mixin
#mixin rwdIE($name, $wrapper-class, $IE: true) {
#if $IE == true {
.lt-ie9 .#{$wrapper-class} {
#content;
}
.#{$wrapper-class} {
#include breakpoint($name) {
#content;
}
}
}
#else if $IE == false {
.#{$wrapper-class} {
#include breakpoint($name) {
#content;
}
}
}
}
Here if you pass a piece of Sass(SCSS) like this
#include rwdIE(456, test) {
background-color: #d13400;
}
it will return this code
.lt-ie9 .test {
background-color: #d13400;
}
#media (min-width: 28.5em) {
.test {
background-color: #d13400;
}
}
This will give you the you the IE and 'new browser' CSS in one file. If you write -
#include rwdIE(456, test, false) {
background-color: #d13400;
}
You will get -
#media (min-width: 28.5em) {
.test {
background-color: #d13400;
}
}
I hope this helps, I've got this on a codepen here too - http://codepen.io/sturobson/pen/CzGuI

There is a CSS3 Mixin I use that has a variable for IE filters. You could do something similar by having a global variable, $forIE or something, wrap the media query mixin within an if and then generate the stylesheet with or w/o the queries.
#if $forIE == 0 {
// Media Query Mixin
}
Or use the #if to import a 3rd scss (_forIE.scss?) that will override things with your IE specific styles.

Related

pass global value css in #media [duplicate]

I am trying to use CSS variables in media query and it does not work.
:root {
--mobile-breakpoint: 642px;
}
#media (max-width: var(--mobile-breakpoint)) {
}
From the spec,
The var() function can be used in place of any part of a value in
any property on an element. The var() function can not be used as
property names, selectors, or anything else besides property values.
(Doing so usually produces invalid syntax, or else a value whose
meaning has no connection to the variable.)
So no, you can't use it in a media query.
And that makes sense. Because you can set --mobile-breakpoint e.g. to :root, that is, the <html> element, and from there be inherited to other elements. But a media query is not an element, it does not inherit from <html>, so it can't work.
This is not what CSS variables are trying to accomplish. You can use a CSS preprocessor instead.
As Oriol has answered, CSS Variables Level 1’s var() cannot currently be used in media queries. However, there have been recent developments that will address this problem. Once CSS Environment Variables Module Level 1 is standardized and implemented, we’ll be able to use env() variables in media queries in all modern browsers.
The CSS Working Group (CSSWG) codified env() in a new standard (currently at a draft stage): the CSS Environment Variables Module Level 1 (see this GitHub comment and this comment for more info). The draft calls out variables in media queries as an explicit use case:
Because environment variables don’t depend on the value of anything drawn from a particular element, they can be used in places where there is no obvious element to draw from, such as in #media rules, where the var() function would not be valid.
If you read the specification and have a concern, or if you want to voice your support for the media-query use case, you can do so in issue #2627, in issue #3578, or in any CSS GitHub issue labeled with “css-env-1”.
GitHub issue #2627 and GitHub issue #3578 are devoted to custom environmental variables in media queries.
Original answer from 2017-11-09:
Recently, the CSS Working Group decided that CSS Variables Level 2 will support user-defined environment variables using env(), and they will try to make them be valid in media queries. The Group resolved this after Apple first proposed standard user-agent properties, shortly before the official announcement of iPhone X in September 2017 (see also WebKit: “Designing Websites for iPhone X” by Timothy Horton). Other browser representatives then agreed they would be generally useful across many devices, such as television displays and ink printing with bleed edges. (env() used to be called constant(), but that has now been deprecated. You might still see articles that refer to the old name, such as this article by Peter-Paul Koch.) After some weeks passed, Cameron McCormack of Mozilla realized that these environment variables would be usable in media queries, and Tab Atkins, Jr. of Google then realized that user-defined environment variables would be especially useful as global, non-overridable root variables usable in media queries. Now, Dean “Dino” Jackson of Apple will join Atkins in editing Level 2.
You can subscribe to updates on this matter in w3c/csswg-drafts GitHub issue #1693 (for especially relevant historical details, expand the meeting logs embedded in the CSSWG Meeting Bot’s resolutions and search for “MQ”, which stands for “media queries”).
What you can do however is #media query your :root statement!
:root {
/* desktop vars */
}
#media screen and (max-width: 479px) {
:root {
/* mobile vars */
}
}
Totally works in Chrome, Firefox and Edge at least the latest production versions as of this posting.
One limitation: if you need to access the value as a variable – for example to use in calculations elsewhere – you will need to have a variable, and it requires defining the variable in two places: the media query and variable declaration.
Apparently it's just not possible to use native CSS variables like that. It's one of the limitations.
A clever way to use it is to change your variables in the media-query, to impact all your style. I recommend this article.
:root {
--gutter: 4px;
}
section {
margin: var(--gutter);
}
#media (min-width: 600px) {
:root {
--gutter: 16px;
}
}
One way to achieve what you want is using npm package postcss-media-variables.
If you are fine with using npm packages then you can take a look documentation for same here:
postcss-media-variables
Example
/* input */
:root {
--min-width: 1000px;
--smallscreen: 480px;
}
#media (min-width: var(--min-width)) {}
#media (max-width: calc(var(--min-width) - 1px)) {}
#custom-media --small-device (max-width: var(--smallscreen));
#media (--small-device) {}
The level 5 specification of media queries define Custom Media Queries that does almost what you are looking for. It allows you to define breakpoint similar to how you do with CSS variables and later use them in different places.
Example from the specification:
#custom-media --narrow-window (max-width: 30em);
#media (--narrow-window) {
/* narrow window styles */
}
#media (--narrow-window) and (script) {
/* special styles for when script is allowed */
}
There is still no support for this actually so we have to wait before using this feature.
Short Answer
You can use JavaScript to change the value of media queries and set it to the value of a css variable.
// get value of css variable
getComputedStyle(document.documentElement).getPropertyValue('--mobile-breakpoint'); // '642px'
// search for media rule
var mediaRule = document.styleSheets[i].cssRules[j];
// update media rule
mediaRule.media.mediaText = '..'
Long Answer
I wrote a small script which you can include on your page. It replaces every media rule with a value of 1px with the value of the css variable --replace-media-1px, rules with value 2px with --replace-media-2px and so on. This works for the media queries with, min-width, max-width, height, min-height and max-height even when they are connected using and.
JavaScript:
function* visitCssRule(cssRule) {
// visit imported stylesheet
if (cssRule.type == cssRule.IMPORT_RULE)
yield* visitStyleSheet(cssRule.styleSheet);
// yield media rule
if (cssRule.type == cssRule.MEDIA_RULE)
yield cssRule;
}
function* visitStyleSheet(styleSheet) {
try {
// visit every rule in the stylesheet
var cssRules = styleSheet.cssRules;
for (var i = 0, cssRule; cssRule = cssRules[i]; i++)
yield* visitCssRule(cssRule);
} catch (ignored) {}
}
function* findAllMediaRules() {
// visit all stylesheets
var styleSheets = document.styleSheets;
for (var i = 0, styleSheet; styleSheet = styleSheets[i]; i++)
yield* visitStyleSheet(styleSheet);
}
// collect all media rules
const mediaRules = Array.from(findAllMediaRules());
// read replacement values
var style = getComputedStyle(document.documentElement);
var replacements = [];
for (var k = 1, value; value = style.getPropertyValue('--replace-media-' + k + 'px'); k++)
replacements.push(value);
// update media rules
for (var i = 0, mediaRule; mediaRule = mediaRules[i]; i++) {
for (var k = 0; k < replacements.length; k++) {
var regex = RegExp('\\((width|min-width|max-width|height|min-height|max-height): ' + (k+1) + 'px\\)', 'g');
var replacement = '($1: ' + replacements[k] + ')';
mediaRule.media.mediaText = mediaRule.media.mediaText.replace(regex, replacement);
}
}
CSS:
:root {
--mobile-breakpoint: 642px;
--replace-media-1px: var(--mobile-breakpoint);
--replace-media-2px: ...;
}
#media (max-width: 1px) { /* replaced by 642px */
...
}
#media (max-width: 2px) {
...
}
You can build a media query programmatically using matchMedia:
const mobile_breakpoint = "642px";
const media_query = window.matchMedia(`(max-width: ${mobile_breakpoint})`);
function toggle_mobile (e) {
if (e.matches) {
document.body.classList.add("mobile");
} else {
document.body.classList.remove("mobile");
}
}
// call the function immediately to set the initial value:
toggle_mobile(media_query);
// watch for changes to update the value:
media_query.addEventListener("change", toggle_mobile);
Then, instead of using a media query in your CSS file, apply the desired rules when body has the mobile class:
.my-div {
/* large screen rules */
}
.mobile .my-div {
/* mobile screen rules */
}
As you can read other answers, still not possible to do so.
Someone mentioned custom environmental variables (similar to custom css variables env() instead of var()), and the principle is sound, though there are still 2 major issues:
weak browser support
so far there is no way to define them (but probably will be in the future, as this is so far only an unofficial draft)

How do I use CSS env variables in media query width values? [duplicate]

I am trying to use CSS variables in media query and it does not work.
:root {
--mobile-breakpoint: 642px;
}
#media (max-width: var(--mobile-breakpoint)) {
}
From the spec,
The var() function can be used in place of any part of a value in
any property on an element. The var() function can not be used as
property names, selectors, or anything else besides property values.
(Doing so usually produces invalid syntax, or else a value whose
meaning has no connection to the variable.)
So no, you can't use it in a media query.
And that makes sense. Because you can set --mobile-breakpoint e.g. to :root, that is, the <html> element, and from there be inherited to other elements. But a media query is not an element, it does not inherit from <html>, so it can't work.
This is not what CSS variables are trying to accomplish. You can use a CSS preprocessor instead.
As Oriol has answered, CSS Variables Level 1’s var() cannot currently be used in media queries. However, there have been recent developments that will address this problem. Once CSS Environment Variables Module Level 1 is standardized and implemented, we’ll be able to use env() variables in media queries in all modern browsers.
The CSS Working Group (CSSWG) codified env() in a new standard (currently at a draft stage): the CSS Environment Variables Module Level 1 (see this GitHub comment and this comment for more info). The draft calls out variables in media queries as an explicit use case:
Because environment variables don’t depend on the value of anything drawn from a particular element, they can be used in places where there is no obvious element to draw from, such as in #media rules, where the var() function would not be valid.
If you read the specification and have a concern, or if you want to voice your support for the media-query use case, you can do so in issue #2627, in issue #3578, or in any CSS GitHub issue labeled with “css-env-1”.
GitHub issue #2627 and GitHub issue #3578 are devoted to custom environmental variables in media queries.
Original answer from 2017-11-09:
Recently, the CSS Working Group decided that CSS Variables Level 2 will support user-defined environment variables using env(), and they will try to make them be valid in media queries. The Group resolved this after Apple first proposed standard user-agent properties, shortly before the official announcement of iPhone X in September 2017 (see also WebKit: “Designing Websites for iPhone X” by Timothy Horton). Other browser representatives then agreed they would be generally useful across many devices, such as television displays and ink printing with bleed edges. (env() used to be called constant(), but that has now been deprecated. You might still see articles that refer to the old name, such as this article by Peter-Paul Koch.) After some weeks passed, Cameron McCormack of Mozilla realized that these environment variables would be usable in media queries, and Tab Atkins, Jr. of Google then realized that user-defined environment variables would be especially useful as global, non-overridable root variables usable in media queries. Now, Dean “Dino” Jackson of Apple will join Atkins in editing Level 2.
You can subscribe to updates on this matter in w3c/csswg-drafts GitHub issue #1693 (for especially relevant historical details, expand the meeting logs embedded in the CSSWG Meeting Bot’s resolutions and search for “MQ”, which stands for “media queries”).
What you can do however is #media query your :root statement!
:root {
/* desktop vars */
}
#media screen and (max-width: 479px) {
:root {
/* mobile vars */
}
}
Totally works in Chrome, Firefox and Edge at least the latest production versions as of this posting.
One limitation: if you need to access the value as a variable – for example to use in calculations elsewhere – you will need to have a variable, and it requires defining the variable in two places: the media query and variable declaration.
Apparently it's just not possible to use native CSS variables like that. It's one of the limitations.
A clever way to use it is to change your variables in the media-query, to impact all your style. I recommend this article.
:root {
--gutter: 4px;
}
section {
margin: var(--gutter);
}
#media (min-width: 600px) {
:root {
--gutter: 16px;
}
}
One way to achieve what you want is using npm package postcss-media-variables.
If you are fine with using npm packages then you can take a look documentation for same here:
postcss-media-variables
Example
/* input */
:root {
--min-width: 1000px;
--smallscreen: 480px;
}
#media (min-width: var(--min-width)) {}
#media (max-width: calc(var(--min-width) - 1px)) {}
#custom-media --small-device (max-width: var(--smallscreen));
#media (--small-device) {}
The level 5 specification of media queries define Custom Media Queries that does almost what you are looking for. It allows you to define breakpoint similar to how you do with CSS variables and later use them in different places.
Example from the specification:
#custom-media --narrow-window (max-width: 30em);
#media (--narrow-window) {
/* narrow window styles */
}
#media (--narrow-window) and (script) {
/* special styles for when script is allowed */
}
There is still no support for this actually so we have to wait before using this feature.
Short Answer
You can use JavaScript to change the value of media queries and set it to the value of a css variable.
// get value of css variable
getComputedStyle(document.documentElement).getPropertyValue('--mobile-breakpoint'); // '642px'
// search for media rule
var mediaRule = document.styleSheets[i].cssRules[j];
// update media rule
mediaRule.media.mediaText = '..'
Long Answer
I wrote a small script which you can include on your page. It replaces every media rule with a value of 1px with the value of the css variable --replace-media-1px, rules with value 2px with --replace-media-2px and so on. This works for the media queries with, min-width, max-width, height, min-height and max-height even when they are connected using and.
JavaScript:
function* visitCssRule(cssRule) {
// visit imported stylesheet
if (cssRule.type == cssRule.IMPORT_RULE)
yield* visitStyleSheet(cssRule.styleSheet);
// yield media rule
if (cssRule.type == cssRule.MEDIA_RULE)
yield cssRule;
}
function* visitStyleSheet(styleSheet) {
try {
// visit every rule in the stylesheet
var cssRules = styleSheet.cssRules;
for (var i = 0, cssRule; cssRule = cssRules[i]; i++)
yield* visitCssRule(cssRule);
} catch (ignored) {}
}
function* findAllMediaRules() {
// visit all stylesheets
var styleSheets = document.styleSheets;
for (var i = 0, styleSheet; styleSheet = styleSheets[i]; i++)
yield* visitStyleSheet(styleSheet);
}
// collect all media rules
const mediaRules = Array.from(findAllMediaRules());
// read replacement values
var style = getComputedStyle(document.documentElement);
var replacements = [];
for (var k = 1, value; value = style.getPropertyValue('--replace-media-' + k + 'px'); k++)
replacements.push(value);
// update media rules
for (var i = 0, mediaRule; mediaRule = mediaRules[i]; i++) {
for (var k = 0; k < replacements.length; k++) {
var regex = RegExp('\\((width|min-width|max-width|height|min-height|max-height): ' + (k+1) + 'px\\)', 'g');
var replacement = '($1: ' + replacements[k] + ')';
mediaRule.media.mediaText = mediaRule.media.mediaText.replace(regex, replacement);
}
}
CSS:
:root {
--mobile-breakpoint: 642px;
--replace-media-1px: var(--mobile-breakpoint);
--replace-media-2px: ...;
}
#media (max-width: 1px) { /* replaced by 642px */
...
}
#media (max-width: 2px) {
...
}
You can build a media query programmatically using matchMedia:
const mobile_breakpoint = "642px";
const media_query = window.matchMedia(`(max-width: ${mobile_breakpoint})`);
function toggle_mobile (e) {
if (e.matches) {
document.body.classList.add("mobile");
} else {
document.body.classList.remove("mobile");
}
}
// call the function immediately to set the initial value:
toggle_mobile(media_query);
// watch for changes to update the value:
media_query.addEventListener("change", toggle_mobile);
Then, instead of using a media query in your CSS file, apply the desired rules when body has the mobile class:
.my-div {
/* large screen rules */
}
.mobile .my-div {
/* mobile screen rules */
}
As you can read other answers, still not possible to do so.
Someone mentioned custom environmental variables (similar to custom css variables env() instead of var()), and the principle is sound, though there are still 2 major issues:
weak browser support
so far there is no way to define them (but probably will be in the future, as this is so far only an unofficial draft)

Best way to support mobile first for IE8 without script?

I am using SASS, Compass, Bourbon and Neat to create a wonderful responsive website.
However, it has dawned on me that IE8 (with its lack of Media Query support) would simply output the mobile version only, because I am using the mobile first approach.
Is there any way to use SASS to generate styles for IE8 automatically, with all the largest media queries converted as the default? I'd like IE8 to get the full desktop look only.
I want to avoid using scripts like respond.js, due to performance and also maintenance down the line.
Solution:
I am using Compass with the Bourbon SASS library. Bourbon has a media() mixin that I wanted to use.
Following on from the selected answer below, I ended up creating a simple wrapper mixin for the media() mixin provided by bourbon.
#mixin bp($bp) {
#if $desktop-only {
#content;
}
#else {
#include media($bp) {
#content;
}
}
}
In my ie.scss file (used by Compass) I set the $desktop-only variable to true. This removes the media query itself and simply places in the attributes that would have been within the query. Because their order is later in the compiled CSS, it takes precedence over the mobile only setting and IE then uses that style.
It results in a slightly bloated CSS fie, but it's worth it as no additional scripts are needed to make it render the desktop version.
I've written a solution for this myself. All you need is two different CSS files (one for modern browsers and one for older IE browsers) and a cleaver mixin.
Create a second SASS file which Compass can watch and call the file something like oldIE.scss. Copy all the imports from you original SASS file (styles.scss or whatever) to this file. Then put a new variable in both of them: $compile-IE. Set the values like this:
styles.scss
$compile-IE: false;
#import "all your other imports"
oldIE.scss
$compile-IE: true;
#import "all your other imports"
Compass will now create two different CSS files for you. You can place them in the HEAD of your Markup like this:
<link type="text/css" href="styles.css" rel="stylesheet" media="all" />
<!--[if (gte IE 6) & (lte IE 8)]>
<link type="text/css" href="oldIE.css" rel="stylesheet" media="all" />
<![endif]-->
Once you have the two files in place, you can start writing SASS with your breakpoints thanks to the following mixin:
// ----- Media-queries ----- //
$breakpoints: S 480px, M 600px, L 769px;
#mixin bp($bp) {
// If compile-IE is true (IE8 <=) then just use the desktop overrides and parse them without #media queries
#if $compile-IE {
#content;
}
// If compile-IE is false (modern browsers) then parse the #media queries
#else {
#each $breakpoint in $breakpoints {
#if $bp == nth($breakpoint, 1) {
#media (min-width: nth($breakpoint, 2)) {
#content;
}
}
}
}
}
Call the mixin as following:
p {
color: blue;
font-size: 16px;
#include bp(L) {
font-size: 13px;
}
}
Now, if the variable $compile-IE is false (for modern browsers) the output will be this:
p {
color: blue;
font-size: 16px; }
#media (min-width: 768px) {
p {
font-size: 13px;
}
}
And when the variable $compile-IE is true (for older IE versions) the output will be this:
p {
color: blue;
font-size: 16px;
font-size: 13px;
}
Because the font-size: 13px is the parsed after the font-size: 16px the styles used for larger viewports (like bp L) will override the default mobile styling.
Hope this will help for you! :)

Media Query grouping instead of multiple scattered media queries that match

I'm experimenting with LESS (not a fan of the SASS syntax) and have been trying to find out what the best way to do media queries with it would be.
I read through this blog post on how to "do" media queries with LESS, but it points out the fact that this causes all the media queries to be separated and scattered throughout the resulting CSS. This doesn't really bother me (I could care less about the result and more about it working). What did bother me was a comment that talked about issues when viewing from iOS devices and the commenter found that once the media queries were consolidated the issue was resolved.
Has anyone found a good solution for using media queries with LESS?
The way I invision this working would be something like...
//Have an overall structure...
.overall(){
//Have ALL your CSS that would be modified by media queries and heavily use
//variables that are set inside of each media queries.
}
#media only screen and (min-width: 1024px){
//Define variables for this media query (widths/etc)
.overall
}
I understand that there could be some issues with this, but the current setup doesn't seem to be that beneficial.
So I guess my question is if there have been any good solutions/hacks to allow for grouped media queries?
(Just incase it matters I use dotless as the engine to parse my .less files)
First, your solution given in the question certainly has some usefulness to it.
One thing I thought, however, was that it would be nice to define all the media query variables "near" one another (your solution would have them under each media query call). So I propose the following as an alternative solution. It also has drawbacks, one being perhaps a bit more coding up front.
LESS Code
//define our break points as variables
#mediaBreak1: 800px;
#mediaBreak2: 1024px;
#mediaBreak3: 1280px;
//this mixin builds the entire media query based on the break number
.buildMediaQuery(#min) {
#media only screen and (min-width: #min) {
//define a variable output mixin for a class included in the query
.myClass1(#color) {
.myClass1 {
color: #color;
}
}
//define a builder guarded mixin for each break point of the query
//in these is where we change the variable for the media break (here, color)
.buildMyClass1() when (#min = #mediaBreak1) {
.myClass1(red);
}
.buildMyClass1() when (#min = #mediaBreak2) {
.myClass1(green);
}
.buildMyClass1() when (#min = #mediaBreak3) {
.myClass1(blue);
}
//call the builder mixin
.buildMyClass1();
//define a variable output mixin for a nested selector included in the query
.mySelector1(#fontSize) {
section {
width: (#min - 40);
margin: 0 auto;
a {
font-size: #fontSize;
}
}
}
//Again, define a builder guarded mixin for each break point of the query
//in these is where we change the variable for the media break (here, font-size)
.buildMySelector1() when (#min = #mediaBreak1) {
.mySelector1(10px);
}
.buildMySelector1() when (#min = #mediaBreak2) {
.mySelector1(12px);
}
.buildMySelector1() when (#min = #mediaBreak3) {
.mySelector1(14px);
}
//call the builder mixin
.buildMySelector1();
//ect., ect., etc. for as many parts needed in the media queries.
}
}
//call our code to build the queries
.buildMediaQuery(#mediaBreak1);
.buildMediaQuery(#mediaBreak2);
.buildMediaQuery(#mediaBreak3);
CSS Output
#media only screen and (min-width: 800px) {
.myClass1 {
color: #ff0000;
}
section {
width: 760px;
margin: 0 auto;
}
section a {
font-size: 10px;
}
}
#media only screen and (min-width: 1024px) {
.myClass1 {
color: #008000;
}
section {
width: 984px;
margin: 0 auto;
}
section a {
font-size: 12px;
}
}
#media only screen and (min-width: 1280px) {
.myClass1 {
color: #0000ff;
}
section {
width: 1240px;
margin: 0 auto;
}
section a {
font-size: 14px;
}
}
For responsive Wordpress sites I use a starter theme called Bones by Eddie Machado ( http://themble.com/bones/ ). I rather like the way it uses media queries, it has different stylesheets for different breakpoints (480+, 768+ etc) which you can change depending on your design.
It then imports these with #import into one stylesheet underneath the appropriate media queries. You edit all of these in LESS and, I use Simpless by Kiss ( http://wearekiss.com/simpless ) to compile my .less stylesheets into .css automatically. I really find it a really good starting point for developing a simple responsive site. Even if you're not developing in Wordpress you may want to check out how they're structured their media queries as it all seems to work fine even with the use if LESS.

Where to put CSS3 media queries?

I am having a philosophical debate with myself over the best place to put media queries within style sheets. I am attempting to structure my CSS modularly (like OOCSS or SMACSS, etc). Given that context, I see two choices:
Put all media queries together in a separate stylesheet or section of the main stylesheet.
Put media queries below their base counterparts. For example, if I have a module called "news-item", I could put any necessary media query styles right below the definition of that module.
I am leaning towards the latter, but it would mean I'd have many more separate media queries (separate ones for each logical block of CSS requiring a responsive adjustment).
Any thoughts on this?
How about using media queries just to load device specific stylesheets
like:
#import url(mydevice.css) this and (that);
or:
<link rel="stylesheet" media="only this and (that)" href="mydevice.css" />
...if you're looking at the device specific adjustments as a kind of "subthemes" to a main layout (just overwriting some properties), this would make sense to me, too.
Approach #2 works better for me.
When I was a newbie, I was using Approach #1 - I was writing my media queries together (at the bottom of my stylesheet or in another file).
.header { ... }
.news-item { ... }
.footer { ... }
/**
* ...
*
* bla bla, imagine a huge amount of styles here
*
* ...
*/
/** All style tweaks for screens < 1024px */
#media screen and (max-width: 1024px) {
.header { ... }
.news-item { ... }
}
This approach has a few downsides. Based on my experience, the most notable one is that the maintainability is a hard. The main reason: .news-item logic is spread across multiple unrelated lines of CSS.
Later on, naturally, I decided to keep the related styles together. Approach #2:
/** Header's styles and media queries */
.header {
...
}
#media screen and (max-width: 1024px) {
.header { ... }
}
#media screen and (max-width: 720px) {
.header { ... }
}
/** News-item's styles and media queries */
.news-item {
...
}
#media screen and (max-width: 1024px) {
.news-item { ... }
}
#media screen and (max-width: 720px) {
.news-item { ... }
}
/** ... and so on */
However, in this approach, repeating media queries max-width values all-around doesn’t look maintainable enough. I solved this issue by using a CSS pre-processor (like SASS) that allows me to replace all them with variables and define them once.
To boost up the maintainability and to make these definitions a lot more elegant I started to use an abstraction on top of the Media Queries.
If you're interested in more details, please read on my blog post :-)
With Sass it's easier to use the media queries directly below the counterparts. But if your CSS is well commented in your modules, I don't see a problem to put the queries bellow since that would be easy to find.
You'll end up writing a little more code retyping the queries, but not a big deal.
May be you can try css variables, which is native support reuse your css!
:root {
--main-color: #F06D06;
}
.main-header {
color: var(--main-color);
}
.main-footer {
background-color: var(--main-color);
}
https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables
https://developers.google.com/web/updates/2016/02/css-variables-why-should-you-care
https://css-tricks.com/difference-between-types-of-css-variables/

Resources