2

My media query rulesets for h1 elements doesn't take effect unless I add !important. Why won't it work on its own?

Media queries:

/* Small devices (landscape phones) */
@media screen and (max-width: 767px) {
    h1 {
        font-size: 1.6em !important;
    }
}

/* Tablets */
@media screen and (max-width: 991px) {
    h1 {
        font-size: 1.7rem;
    }
}

/* Small laptops */
@media screen and (max-width: 1199px) {
    h1 {
        font-size: 2rem;
    }
}
nCardot
  • 5,992
  • 6
  • 47
  • 83
  • !important overrides any default css property. It is a hack but it works, and is widely supported. – Victor Stoddard May 05 '18 at 03:33
  • See [this](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity) – Athul Nath May 05 '18 at 03:45
  • 1
    The order of your css matters. How specific your css also matters. Please edit your question to include only the relevant part of the code, and show the order of the affected CSS – Ibu May 05 '18 at 05:06
  • You may have browser extensions or plug-ins that change the effective css. – Grim May 05 '18 at 05:30

2 Answers2

1

Because there is a later style that will override it and it's the one in the last media query:

@media screen and (max-width: 1199px) {
  h1 {
    font-size: 2rem;
  }
}

So if we only consider the styles of your h1 we have this CSS:

h1 {
  color: #2d3c49;
  text-transform: uppercase;
}

h1 {
  font-weight: 200;
  font-size: 2.6em;
  margin-bottom: 0;
}

@media screen and (max-width: 767px) {
  h1 {
    font-size: 1.6em;
  }
}

@media screen and (max-width: 991px) {
  h1 {
    font-size: 1.7rem;
  }
}

/* This one will always win the race !*/
@media screen and (max-width: 1199px) {
  h1 {
    font-size: 2rem;
  }
}
<h1>Natalie Cardot</h1>

So when you screen is lower than 767px it's also lower than 1199px that's why your style defined within the first media query is not considered and you are obliged to use !important. To avoid this you need to re-order your media query like this:

h1 {
  color: #2d3c49;
  text-transform: uppercase;
}

h1 {
  font-weight: 200;
  font-size: 2.6em;
  margin-bottom: 0;
}


@media screen and (max-width: 1199px) {
  h1 {
    font-size: 2rem;
  }
}
@media screen and (max-width: 991px) {
  h1 {
    font-size: 1.7rem;
  }
}
@media screen and (max-width: 767px) {
  h1 {
    font-size: 1.6em;
  }
}
<h1>Natalie Cardot</h1>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
-3

h1 tag has a default size ,inorder to override it you need !important

Faizal Hussain
  • 1,551
  • 2
  • 10
  • 18