jviotti
jviotti

Reputation: 18939

CSS Precedence and media queries

I have .cssClass containing:

// fallback without calc
width: 60%; 
@media (max-width: 500px) { width: 58%; }
@media (max-width: 460px) { width: 55%; }
@media (max-width: 420px) { width: 50%; }
@media (max-width: 380px) { width: 45%; }
@media (max-width: 340px) { width: 40%; }
// using calc
width: -webkit-calc(70% - (34px + 1.12em));
width: -moz-calc(70% - (34px + 1.12em));
width: -ms-calc(70% - (34px + 1.12em));
width: -o-calc(70% - (34px + 1.12em));
width: calc(70% - (34px + 1.12em));

So if the browser supports calc, It will replace the previously defined width (60%) and It will use the calc approach.

However It's still using the media-queries when resizing, replacing the calc value with the queries values.

I'm getting a good result in browsers that don't support calc, because it's just ommiting all that stuff, but browsers that do support calc, obtain the calc result mixed with the fallback queries.

What should I do? I only want the media-queries to run if there's no calc support.

I'm looking for a solution or another approach without involving JavaScript.

Upvotes: 3

Views: 1289

Answers (1)

3dgoo
3dgoo

Reputation: 15794

SASS will sort nested properties to have media queries last.

Here are some examples of what happens:

SCSS

body {
    background: #000000; //black

    @media (max-width: 500px) { 
        background: #990000; //red
    }

    background: #000099; //blue

    @media (max-width: 300px) { 
        background: #009900; //green
    }
}

Output CSS

body {
    background:#000;
    background:#009
}
@media (max-width: 500px) {
    body {
        background:#900
    }
}
@media (max-width: 300px) {
    body {
        background:#090
    }
}

Demo

What you can do is put in a second nest to manipulate the sort order:

SCSS

body {
    background: #000000; //black

    @media (max-width: 500px) { 
        background: #990000; //red
    }


}
body {
    background: #000099; //blue

    @media (max-width: 300px) { 
        background: #009900; //green
    }
}

Output CSS

body {
    background:#000
}
@media (max-width: 500px) {
    body {
        background:#900
    }
}
body {
    background:#009
}
@media (max-width: 300px) {
    body {
        background:#090
    }
}

Demo

So you can do this with your code and it should sort in the correct order:

SCSS

.cssClass {
    // fallback without calc
    width: 60%; 
    @media (max-width: 500px) { width: 58%; }
    @media (max-width: 460px) { width: 55%; }
    @media (max-width: 420px) { width: 50%; }
    @media (max-width: 380px) { width: 45%; }
    @media (max-width: 340px) { width: 40%; }
}
.cssClass {
    // using calc
    width: -webkit-calc(70% - (34px + 1.12em));
    width: -moz-calc(70% - (34px + 1.12em));
    width: -ms-calc(70% - (34px + 1.12em));
    width: -o-calc(70% - (34px + 1.12em));
    width: calc(70% - (34px + 1.12em));
}

Upvotes: 3

Related Questions