Where to put CSS3 media queries? - css

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/

Related

What is the purpose of including "all" in #media rules?

So you see a lot of code examples do something like
#media all and (max-width:640px) {
div {
background-color:red;
}
}
Now afaik, the keywords "all" and "screen" and some others are for selecting the device type this applies to and the line is just supposed to provide a boolean output.
Since "all" applies to every device, one would imagine that its always 1 and (1 && x) always equals x so "all and" should make no difference whatsoever.
I tried out
#media (max-width:640px) {
div {
background-color:red;
}
}
and at least my browsers agree. Is there anything else I should know about?
See the spec: https://www.w3.org/TR/css3-mediaqueries/
The ‘print’ and ‘screen’ media types are defined in HTML4. The complete list of media types in HTML4 is: ‘aural’, ‘braille’, ‘handheld’, ‘print’, ‘projection’, ‘screen’, ‘tty’, ‘tv’. CSS2 defines the same list, deprecates ‘aural’ and adds ‘embossed’ and ‘speech’. Also, ‘all’ is used to indicate that the style sheet applies to all media types.
...
A shorthand syntax is offered for media queries that apply to all media types; the keyword ‘all’ can be left out (along with the trailing ‘and’). I.e. if the media type is not explicitly given it is ‘all’.
/* I.e. these are identical: */
#media all and (min-width:500px) { … }
#media (min-width:500px) { … }
/* As are these: */
#media (orientation: portrait) { … }
#media all and (orientation: portrait) { … }
In addition, the following media types: 'tty', 'tv', 'projection', 'handheld', 'braille', 'embossed', 'aural' have been deprecated in Media Queries Level 4.
all refers to: all media type devices, print: used for printing, screen: used for desktop screens, mobiles, tablets etc and speech: used for screen-readers that "reads" the page out loud.
In your case where you have specified media type as all, you can try printing the page by right clicking. The printed page will have all the styles applied in short it will exactly look the same.
Now take another example where you specify the media type as screen. If you try to print the page you will not see all the styles getting applied to the page as the styles were defined for screen alone.
If one does not specify all in media query it is by default taken as all.
#media screen {
div {
color: blue;
}
.print{
display: none;
}
}
#media print and (min-width: 200px){
div{
color: tomato;
}
div.not('.example'){
display:none !important;
}
.print{
display: block;
}
}
<div class="example">
<div>Try printing me. See if this blue color appears while printing</div>
<div class="print">I am only visible while printing.</div>
</div>

Media query not working in one environment, but working in another

I have a LESS environment that is bringing together multiple files and putting everything together into a massive .CSS file (forced to work this way).
However, in one environment the "#media (min-width: 768px) and (max-width: 979px)" declaration is being validated and the custom CSS for it is rendering properly in all instances. However, in another environment with the exact same media query and CSS, it is not even acknowledging it within the CSS file.
Working environment: giving.massgeneral.org
[CSS^] https://www.dropbox.com/s/4hxtevg0ft0hsae/base.css
Non-working environment: secure.massgeneral.org/bootstrap-library
[CSS^] https://www.dropbox.com/s/ncrbgxs2ot184cm/bbnc.css
The most notable issue is the following query that is completely being ignored in the "secure." environment:
// Tablets & small desktops only
#media (min-width: 768px) and (max-width: 979px) {
// Hide everything else
.hidden-desktop { display: inherit !important; }
.visible-desktop { display: none !important; }
// Show
.visible-tablet { display: inherit !important; }
// Hide
.hidden-tablet { display: none !important; }
}
It is successfully generating this code and placing it into the "bbnc.css" file, however, it is not associating the styles with the classes above when in the viewport designated in the "secure." environment.
Any advice outside would be greatly appreciate on getting this to validate.

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.

How Should CSS3 Media Queries be Managed?

Since there are many ways to implement CSS3 Media Queries into a website, I would like to know which one is recommended by more experienced web designers. I can think of a couple:
1. All in one Stylesheet
There is a default style which applies to all screen widths, and media queries that apply only to lower screen widths and overwrite the default, all in one file. For example:
HTML
<link rel="stylesheet" href="main.css">
main.css
article
{
width: 1000px;
}
#media only screen and (max-width: 1000px)
{
article
{
width: 700px;
}
}
(please keep in mind that this is just an example)
Pros:
Default style applies to older browsers
Only one HTTP request required
Cons:
Gets messy with a lot of code
Some browsers will have to download code that they won't apply
2. Separate Stylesheets
There are separate stylesheets containing full code tailored for each screen width. Browsers only load the one that applies. For example:
HTML
<link rel="stylesheet" href="large-screen.css" media="screen and (min-width: 1001px)"> /*Also older browsers*/
<link rel="stylesheet" href="small-screen.css" media="only screen and (max-width: 1000px)">
large-screen.css
article
{
width: 1000px;
}
small-screen.css
article
{
width: 700px;
}
Pros:
Neat and organized
Only one HTTP request required
Browsers only load what they need
Cons:
(This is why I'm hesitant to use this:) When one makes a change that applies to all screen widths, the change has to be copied and pasted to the appropriate spots in all of the stylesheets.
3. Separate Stylesheets, one Global Stylesheet
The same as #1, but the global style and the media queries are in separate stylesheets. For example:
HTML
<link rel="stylesheet" href="main.css">
<link rel="stylesheet" href="small-screen.css" media="only screen and (max-width: 1300px)">
main.css
article
{
width: 1000px;
}
small-screen.css
article
{
width: 700px;
}
Pros:
Also neat and managable
Does not have problem of #2 when making global changes
Global style applies to older browsers
Cons:
Smaller screen-widths require 2 HTTP requests
That's all I can think of. How should media queries be managed?
Thanks for any responses.
Well, I certainly can't claim to be an authority on the matter (I'm still learning about coding conventions myself), but I actually lean towards option #1 - a single stylesheet. I'm thinking of a specific implementation of it, though. Instead of having a single break point for each case of screen size you need new styles for, I'd suggest multiple break points - one for the CSS styles of each module where multiple screen sizes need to be addressed.
Ah...that might have been a slightly confusing statement. An example is in order...
Rather than something like:
/*default styles:*/
/*header styles*/
.header-link{ ... }
.header-link:active{ ... }
.header-image{ ... }
.header-image-shown{ ... }
.header-table-cell{ ... }
/*content styles*/
.content-link{ ... }
.content-link:active{ ... }
.content-image{ ... }
.content-image-shown{ ... }
.content-table-cell{ ... }
/*footer styles*/
.footer-link{ ... }
.footer-link:active{ ... }
.footer-image{ ... }
.footer-image-shown{ ... }
.footer-table-cell{ ... }
/*alternate styles for smaller screens:*/
#media only screen and (max-width: 1000px){
/*header styles*/
.header-link{ ... }
.header-image{ ... }
.header-image-shown{ ... }
.header-table-cell{ ... }
/*content styles*/
.content-link{ ... }
.content-image{ ... }
.content-image-shown{ ... }
.content-table-cell{ ... }
/*footer styles*/
.footer-link{ ... }
.footer-image{ ... }
.footer-image-shown{ ... }
.footer-table-cell{ ... }
}
I'd suggest option #1, just implemented as so:
/*default header styles*/
.header-link{ ... }
.header-link:active{ ... }
.header-image{ ... }
.header-image-shown{ ... }
.header-table-cell{ ... }
/*alternate header styles for smaller screens*/
#media only screen and (max-width: 1000px){
.header-link{ ... }
.header-image{ ... }
.header-image-shown{ ... }
.header-table-cell{ ... }
}
/*default content styles*/
.content-link{ ... }
.content-link:active{ ... }
.content-image{ ... }
.content-image-shown{ ... }
.content-table-cell{ ... }
/*alternate content styles for smaller screens*/
#media only screen and (max-width: 1000px){
.content-link{ ... }
.content-image{ ... }
.content-image-shown{ ... }
.content-table-cell{ ... }
}
/*default footer styles*/
.footer-link{ ... }
.footer-link:active{ ... }
.footer-image{ ... }
.footer-image-shown{ ... }
.footer-table-cell{ ... }
/*alternate footer styles for smaller screens*/
#media only screen and (max-width: 1000px){
.footer-link{ ... }
.footer-image{ ... }
.footer-image-shown{ ... }
.footer-table-cell{ ... }
}
(All the classes are placeholders. I'm not very creative...)
Though this means you'll be doing the same media query declaration multiple times (leading to a bit more code), it's a lot more handy for testing out single modules, which will overall help the maintainability of your site as it gets bigger. Try adding multiple real styles, more tags/classes/id's to the example I gave, and maybe add a bit more whitespace to them, and you'll see soon see how much quicker it is to narrow down and change/append styles (across all screen sizes) in the implementation shown by the second part of the example.
And I credit this answer quite completely to information from Scalable and Modular Architecture for CSS, by Jonathan Snook. (After all, there's no way a beginner like me would be able to figure out and reason an answer like that all by myself!) As quoted from one of the many relevant parts of that book,
"...instead of having a single break point, either in a main CSS file or in a seperate media query style sheet, place media queries around the module states."
Though, if by personal preference or other you'd rather not use this approach, then you're free to go with any of the other options you proposed - after all, Snook himself says that his book "is more style guide than rigid framework", so don't feel like this is a coding standard. (Though I feel it should be. XD)
I believe in "putting code where you expect it". If a style needs overruling I would want my code that overrules to be as close to the default style, thus in the same document. That way, a year from now, I will still know what's going on when I look at the code. In the other approach (separate css file per breakpoint) I will need to remember to goo look for overruling styles code in a separate file. Not a problem, unless I forget I did it that way a year from now. Guess it's personal preference and the browser doesn't care.
If you want to use the 2nd option there's a way to avoid "copy+pasting" the global styles that you need for both your mobile and desktop versions of the site which is veeeeeery handy and helps you keep everything more organized in my opinion and that is using SASS.
You could have something like that:
> CSS Folder
> Sass folder
- _global.scss
- _mobile_layout.scss
- _desktop_layout.scss
- main_mobile.scss
- main_desktop.scss
which will compile into
> CSS Folder
- main_mobile.css
- main_desktop.css
Hope you find it useful ^^

SASS 3.2 Media Queries and Internet Explorer Support

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.

Resources