Search code examples
htmlcssmedia-queries

Why does media query only work when placed last in my CSS?


I'm learning css and I came across an example that has the following code:

<body>
   <a href="#" class="CardLink CardLink_Hearts">Hearts</a>
   <a href="#" class="CardLink CardLink_Clubs">Clubs</a>
   <a href="#" class="CardLink CardLink_Spades">Spades</a>
   <a href="#" class="CardLink CardLink_Diamonds">Diamonds</a>
</body>

and css:

.CardLink {
    display: block;
    color: #666;
    text-shadow: 0 2px 0 #efefef;
    text-decoration: none;
    height: 2.75rem;
    line-height: 2.75rem;
    border-bottom: 1px solid #bbb;
    position: relative;
}

@media (min-width: 300px) {
    .CardLink {
        padding-left: 1.8rem;
        font-size: 1.6rem;
    }

    .CardLink:before {
        display: block;
    }
}

.CardLink:before {
    display: none;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    left: 0;
}

.CardLink_Hearts:before {
    content: "❤";
}

.CardLink_Clubs:before {
    content: "♣";
}

.CardLink_Spades:before {
    content: "♠";
}

.CardLink_Diamonds:before {
    content: "♦";
}

/*@media (min-width: 300px) {
    .CardLink:before {
        display: block;
    }
}*/

The idea is when the viewport size is below 300px then the card icons are not displayed, otherwise, it shows them.

I was playing around with the code and I can't understand why we have to define @media (min-width: 300px) twice for the code to work as expected.

Why can't we just put the code in the last paragraph of the css to the section where media screen size belongs (good code reuse instead of declaring this again ) ?

If I do this then no icons are displayed (this is the code below).

Could anyone explain ? Check the plunker, this works as expected: https://plnkr.co/edit/MJAPdkgUegpUlJnkcQHg?p=preview


Solution

  • Because you're working with Cascading Style Sheets.

    A cascade is like a waterfall: The rendering engine starts at the top of the source document and works its way down.

    In this case, it sees your media query. Then it sees the rest of your code, which takes precedence because it comes later.

    For instance, let's say your stylesheet had this:

    div { color: red; }
    
    div { color: blue; }
    
    div { color: red; }
    

    Your text color will be red.

    In this case:

    div { color: red; }
    
    div { color: blue; }
    

    Your text color will be blue.

    In both cases, CSS picks the last declaration in the stylesheet.

    If you want your media query to take precedence, put it at the end of your code.

    (It seems simple and often it is. Just make sure to learn about CSS specificity.)