12

I am trying to make my website responsive. However, when I use another media query, a lot of things won't work. For example:

(Normal CSS)

div#divName
{
    font-size:1em;
}

(Media query code)

@media screen and (max-width: 320px) 
{
    div#divName
    {
        font-size:.5em;
    }
}

This doesn't work. It only works when I use "!important" behind it. But I don't know if that is correct or "wrong". Could anyone tell me how I can fix this?

3
  • 2
    If you want to get around using !important you'll just need a slightly better understanding of the cascade that happens in CSS :) Dec 12, 2014 at 12:24
  • try using classes on your css/html instead of ID's. try to use ID's in html only when you are going to be attaching javascript events etc
    – atmd
    Dec 12, 2014 at 12:24
  • possible duplicate of Why is my CSS media query being ignored?
    – user663031
    Dec 12, 2014 at 12:56

2 Answers 2

19

All !important does is increase specificity. To avoid using !important, all you need to do is increase specificity.

In your case, both of your selectors have identical specificity. The issue is most likely caused by your media query being placed before your "Normal CSS", and thus getting overridden.

  1. If they're in the same CSS file, ensure your "Normal CSS" is placed before your media query.
  2. If they're in different CSS files, ensure the file containing your media query is included in your HTML document after your "Normal CSS".
1
  • Cheers mate! Thank you very much! I did have all media queries above the original code.
    – Rubenxfd
    Dec 12, 2014 at 12:38
1

make sure your CSS rules that you want to override loads after.
in your case

div#divName
{
    font-size:1em;
}

should be loaded first and after that:

@media screen and (max-width: 320px) 
{
    div#divName
    {
        font-size:.5em;
    }
}

you want to have two separated files style.css and responsive.css and include them in following order:

<link href="style.css" rel="stylesheet" /> 
<link href="responsive.css" rel="stylesheet" />

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.