Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  1. Put all media queries together in a separate stylesheet or section of the main stylesheet.
  2. 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?

like image 900
Matt Fordham Avatar asked Jul 03 '12 22:07

Matt Fordham


2 Answers

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.

like image 103
mgherkins Avatar answered Dec 07 '22 03:12

mgherkins


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 :-)

like image 42
Kaloyan Kosev Avatar answered Dec 07 '22 04:12

Kaloyan Kosev