Ordering CSS and Media Queries

I have another question about organizing my CSS and media queries…

In this video that @chrisofarabia turned me on to, the speaker talks about not making the browser yo-yo all over the place as it tries to find the right style.

Sounds like a good idea, but now that my Home Page is finally coded and working, I am starting to see that I have no clue of how to organize my code like this speaker was talking about.

It is a no-brainer to put things like resets and generic things like p{padding: 0 0 1em 0;} at the top of your style sheet, but for everything I have some serious questions.

Question #1:
Is it correct that you should structure your CSS so that the browser skips styles unless they apply? (Almost like how you use an IF-THEN-ELSE in programming?)

If so, how do you do this? And can it be done without using media queries?

Question #2:
If a person is coding “mobile-first”, then technically you should be writing “outlier” styles like for 320px first. Is that really how it goes?

I wrote my styles based on what I see on my MacBook which is 1280x800. Everything from there is an exception.

It seems like it is a more reasonable approach to code for the more common screen-sizes (e.g. 1280px) and then go from there. But doing so kind of invalidates “mobile-first”, right?

(I really hope going from the most common denominator is okay, because otherwise most of my CSS that I have spent the last week or two on is all mixed up?!) :fearful:

Question #3:
In my masthead, I have things coded like this…

/* companyInfo (Mobile) */
@media screen and (max-width: 700px){

}

@media screen and (max-width: 500px){

}

@media screen and (max-width: 425px){

}

The first media query applies to everything under 700px, but the 2nd and 3rd media queries are mutually exclusive.

What is the best way to code this so the browser isn’t looking for styles that won’t apply?

Would this be better…

/* companyInfo (Mobile) */
@media screen and (max-width: 700px){

}

@media screen and (min-width: 0px) and (max-width: 425px){

}

@media screen and (min-width: 426px) and (max-width: 500px){

}

(That would tell the browser to always read the first media query, but to selectively choose either the 2nd or 3rd media query - or skip them both - without unnecessarily reading more than it needs, right?)

All of this might seem nit-picky, but I am trying to learn the best way to structure my CSS and media queries so I don’t have issue down the road.

I also want to make sure my CSS runs as quickly as possible for performance reasons.

So what do you think about my questions and this topic in general?

Have I created a CSS disaster not asking these questions early on?

“Should” may be too strong a word. But it makes sense to do that. It feels dirty to apply a style and then remove it.

Do it with media queries. Target the styles to the screen size they apply to.

There’s no common screen size. That’s the problem. A large chunk of the world uses only phones to access the web.

Rather than think of mobile first or desktop first, I prefer to think of dud browsers first. That is, serve up a basic layout that will work fine on all devices—including small ones and browsers that don’t understand media queries—and then add in fancier stuff via media queries where needed.

Yes, makes more sense to set a range like that. But watch out for this:

max-width: 700px
max-width: 500px
max-width: 425px

Setting so many break points in such a small range will do your head in. Not worth it.

Yes, that’s how the “mobile first” approach works. You start with the default styling, the stuff not in any query, tailored for the smallest mobile. Then add min-width queries to alter the layout for larger screens.

Yes, it’s not “mobile first” this approach is “desktop first”. You are not forced to use mobile first, doing it another way is not “invalid” in any way. There are those who will argue the pros and cons of either method, but in the end, they just mirrors of each other. The choice is yours which you prefer to use.

That sound like a sensible approach, certainly worth consideration. Note this bit:

Remember what I said about the “opposite query”, understand why it’s bad?

I’m not so sure. But it’s impossible to tell without seeing the whole picture, and that never happens with Mikey.
I tend to use the first approach, because styles set in the 500px query most likely continue onto smaller screens too. But there may be circumstances where this has a use, it just smells to me a bit of being too specific for specific sizes. Also I’m not sure what the (min-width: 0px) is for.

It has been mentioned. Apparently:-

But we can only speculate.

Impossible to know until we see a complete page from you, we can only speculate.

1 Like

If a person truly wanted that effect, you would need to do this…

@media screen and (min-width: 0px) and (max-width: 400px){
}

@media screen and (min-width: 401px) and (max-width: 600px){
}

@media screen and (min-width: 601px) and (max-width: 1280px){
}

@media screen and (min-width: 1281px){
}

Is there a performance advantage to being so neurotic?

And is it worth mucking up your style-sheet to do this? (I don’t think @SamA74 would like it… ) :wink:

Again, who can say if this is good or not without the whole picture? We don’t know what css rules are going in each query or the global stuff that is not in any query and we don’t see the html that uses the sheet.
It may be genius, or it may be garbage, who could know?
Generally in CSS (Cascading Style Sheet) you would set the global stuff for the site that will propagate down to all levels. Then you may add a query at a breakpoint that may override some of the rules previously stated.
You may need to add a second breakpoint and override more rules.
The thing is, are the rules you are overriding in the second query the same rules you changed in the first one? If yes, then it ‘may’ have some vaule, but otherwise it looks like unnecessary complication that could cause more problems than it solves, if indeed any problems existed in the first place.

are the rules you are overriding in the second query the same rules you changed in the first one?

I ask because that is not something I would typically do. The rules set in the eariler query would cascade down to lower ones. The lower one would likely have different rules.

I do get what you are trying to do: not dish out any rules that will be overridden. But that would be near impossible without making the sheet rely entirely on queries. You need to have a full set of css rules to make the site work outside of any query.
Please don’t tell me your plan was to have this sheet where the whole css is bound within queries.

True, but I’m not posting my entire website on here for people to steal. And sometimes it takes me half a day to dissect and re-code a simple example to post here which isn’t always practical. I try to provide code, but you have to weigh in the above factors.

I am asking in general, so you shouldn’t need to see my actual code.

At the hardware store you ask, “Should I paint my house using latex paint?”

Does the clerk need to see your house to answer?

“No, man! You never use latex paint on exterior surfaces!”

I think a lot of that applies to many of my questions here… :wink:

Here is something I was just working on… In my masthead, I have a #companyName and #tagline. As the screen increases, I increase the font-size. So I have 3 media queries that keep over-writing the font-size.

#masthead{
    font-size: 0.8rem;
}

@media screen and (min-width: 400px){
    #companyName{
        font-size: 0.9rem;
    }
}


@media screen and (min-width: 700px){
    #companyName{
        font-size: 1rem;
    }
}

If I had a lower and upper bound, then I could avoid overwriting the font several times.

@media screen and (min-width: 0px) and (max-width: 399px{
    #companyName{
        font-size: 0.8rem;
    }
}

@media screen and (min-width: 400px) and (max-width: 699px{
    #companyName{
        font-size: 0.9rem;
    }
}

@media screen and (min-width: 700px){
    #companyName{
        font-size: 1rem;
    }
}

Of course that was a simplified example, but does the second have advantages over the first? In this case, I would say no.

But to the point of that guy in the video that @chrisofarabia posted yesterday, you want to avoid writing and rewriting styles. In responsive design, I think it is inevitable, as the whole idea is that things respond/adapt/progress.

As I am rewriting my CSS today, I am trying to take an approach like the first code block. I start with styles that apply globally and at 320px, and then as the layout gets bigger (e.g. at 500px), I usually add a media query min-width: 500px and either add new styles or overwrite existing ones (e.g. #companyname).

In case like my layout.css sheet, I do have lower and upper bounds, because the elements being styled are vastly different between a mobile and desktop layout, and as I found out, if I just add on a lower bound, then I get a union of the mobile and desktop styles and it breaks.

As I am finding out!

Right now that would be from 0px to maybe 500px. If media queries were not supported, I would be good up to 500px.

Is that likely to happen?

And how would you test your code with media queries turned off?

I think my design would break if I had to rely on CSS that was written only for under 500px. But this is a new concept to which I don’t have an answer…

@media screen and (min-width: 0px) and (max-width: 399px{
    #companyName{
        font-size: 0.8rem;
    }
}

@media screen and (min-width: 400px) and (max-width: 699px{
    #companyName{
        font-size: 0.9rem;
    }
}

@media screen and (min-width: 700px){
    #companyName{
        font-size: 1rem;
    }
}

I sincerely hope that you’re not getting that granular with your media query css - you’re setting yourself up for heartbreak and headaches and maintenance nightmares. Achieving pixel perfection is just nearly impossible, and not worth the aggravation.

From what I’ve used media queries for, it’s more for “big picture” items:

  1. Showing hiding content (I hide the organization logo at small sizes)
  2. Changing menu styles (standard menu for most and hamburger at mobile)
  3. Changing how content is displayed
  4. Tweaking colors schemes (I’ve reversed color schemes to make it easier to read on a mobile device outside)
1 Like

Guilty as charged! :smile:

In fairness, I think I have achieved near perfection - by my standards - on my Home Page, and it wasn’t that hard. I can adjust my browser from 320px to infinity, and everything looks good.

I adjusted the font in the masthead as described above so I could squish everything into a tight spot and keep the look and feel I wanted for the company branding. (I don’t get that cray with the main areas.)

I do a little of both. Big stuff like page layout, but sometimes little stuff like tweaking the masthead a couple times to keep things readable so people know the company name and can see the tele #. (As I get bette with RWD, I am sure I will learn new approaches to reduce my need to change the font for the company name 3 times, but for now it does look near pixel-perfect.

What do you think about @SamA74’s insistence that my site could break if media queries were not supported?

As far as I can see, I would be up a creek anyway, because I heavily rely on media queries for thinks like switching from a display: table layout for desktops to a display:block layout for mobile and need media queries to turn that on and off!

Okaaay. As long as you’re not worried about people who change the default font size of their devices.

Unless you’re really good - I bet @PaulOB could build (and probably has built) a responsive site without media queries, though I doubt he would anymore since it’s the right tool for the right job.

The basic premise is to make something that is clean and easy to maintain, and I think everyone’s points above can be simplified down to:

  • Do not make your job too hard - only use the media queries if you ABSOLUTELY have to - my opinion, the company name pixel perfect is not a “have to” measure.
  • Only include those items in the media query that you MUST change. If you end up with a lot, look at how you’re styling. Can you simplify/generalize it?
  • Limit the number of media queries you have - only use one if you get a tangible benefit. Just because it doesn’t look “bullet proof” isn’t enough
2 Likes

Another similar scenario:

Customer: “Should I paint my wall with latex paint?”

Clerk: “What type of wall is it? Interior or exterior? What surface is it? Bare brick, stone, wood, plaster, plasterboard, hardboard, chipboard, paper, painted?”

Customer: “I’m not telling you.”

Clerk: “Errm, maybe, I don’t know.”

Sooner or later it will be online for all to see, just like everyone else’s. Of course, none of the billions of other sites will be anywhere near as good as yours, so yours is bound to get stolen. :smiley:
But seriously, if you just took the time to mock up a whole dummy page on Codepen or similar, I think it could be a revelation. With you I sometimes feel like the blind leading the blind, because I can’t see what you are talking about, so it’s all guesswork.

So you are re-writing the same rule in each query.
But will there be other rules in the query that you do want to cascade to other sizes? If so, you would need a second version of the query (without both min and max) to contain those rules, or you would repeat those rule in every query that requires it. You will be inflating your css. So would the ‘possible’ performance gain, from skipping overridden rules surpass the performance loss of a bloated css file? I honestly don’t know, but suspect the figures would be negligible enough not to waste time on it.

I think all the modern browsers now support media queries. But there are still some old one out there. And I just feel it’s bad practice to put everything in queries.

Find an old XP machine with IE8 on it.
Finding a mobile with an old enough browser will be harder, though I have one in a drawer at home.

That’s mobile first for you. someone on an old browser will get the mobile view. But is anyone still using ancient (pre css3) smartphones?

I’m not sure about Paul, but I recall @RyanReese talking about using flex-box to make a site with no queries. Of course a browser that doesn’t do queries, wont do flex-box. But the point is, as I have mentioned before, using a more fluid layout system can reduce queries to a minimum.

Agreed. It’s still a good approach to take.

@DaveMaxwell,

Good advice.

As far as media queries go, I suppose you don’t need them IF you can be sure to turn “off” everything you need to.

For instance, I stripped out a media query - after @SamA74’s constant drumbeat - and I broke my layout. Took me forever to see why, but I had an element I styled under 1200px that I was not styling in over 1200px, so without a “wrapper” media query, I had to catch that and turn it “off”. (Somewhat of a PITA.)

Should I be doing things that way so they don’t break, or can I trust that media queries work 99% of the time?

In your default css (whichever way you work mobile first or desktop first), you should be coding stuff in %/em/rem as much as possible, with as few set widths as you can possibly get away with. Then you should use the media queries where ever you need to to catch the places where things break in an unacceptable manner.

Just so you know, Sam, I do care about you… :wink:

Before he passed, Steve and I - that Mr. Jobs to you! - had this talk, and he advised me to keep my brilliant ideas close to my chest. :wink:

One of my big goals for 2016 is to learn to be a better coder - read more efficient.

If I can start doing that, maybe I can do what you ask. But it takes me so long to code my production stuff, and when I come here it is often because I have a problem deep in the boiler-room. It would be nice to post everything, but it isn’t practical.

If I can learn component architecture next year, maybe I can zip things out like @PaulOB

In that case, yes.

And counter to the dude in the video, I think that is okay.

I found that out this morning. So that is a strike for the lower/upper bound approach. And it is why I tried the min-width: 500px, min-width: 700px, min-width: 1280px on my media queries.

You are probably right.

But you need to look at my context.

As it stands now, I may have went a little crazy with my company branding, but I have tried to reduce media queries - and CSS in general - as much as possible.

One place I am very dependent on them is for layout. For instance, I have two completely different menus depending on screen size.

/* Top Menu: Drop-down (Mobile) */
@media screen and (min-width: 0px) and (max-width: 700px){
}

/* Top Menu: Horizontal (Desktop) */
@media screen and (min-width: 701px){
}

If media queries didn’t work, I would be in trouble, but what else would you propose?

How would @PaulOB write the CSS so your code knows when to serve up one menu type versus the other without media queries??

I have been using em’s for years, and even use rem’s now almost exclusively.

I only use px’s for media queries because it is easier for me to think in pixels than em’s when it comes to screen sizes. And since I proved that my home page looks identical whether I use px’s or em’s for my media queries, I prefer px’s there.

For my #masthead, I have 3 media queries to adjust the font/logo/layout for the company branding. And I have 2 media queries for the menu - either a horizontal menu or a drop down for mobile.

For my page layout, I have one media query.

I think I am doing okay so far.

I am.

When I say 6-7 breaks, I mean for the whole page as I adjust my browser. As you see above, I only have one for layout, 3 for the masthead, and a few more for for my sections.

Work in progress…

Assuming that you have reasonable width columns you only need a break every 250 to 400px so seven breaks should cover changing layouts out to about 3000px or more.

Simple, if you are mobile first, that first query is scrapped and its styling is the default.
If it were desktop first, vice-vera.

If the menu is styled drastically different, sure you need a query. If the menu has just 2 states, one is the default and the other goes in the query.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.