0

I have a html code with inline css and also with css media queries While running the inline css is not being replaced by media queries. I need to find a way to add those !important in every style inside the media query dynamically (may be with js). Is there a way to do this other than traversing through to html content as string and finding the styles and adding it. I have added a sample code for reference

  body {
          background-color: yellow;
        }
        @media only screen and (max-width: 600px) {
          body {
            background-color: lightblue;
          }
        }
    <body style="background-color:red;">
    </body>
Udhay Titus
  • 5,761
  • 4
  • 23
  • 41
  • 1
    No, you need a script, and I wouldn't loop and add _!important_ to your external CSS. Instead loop and remove the inline `style` attribute. `document.querySelectorAll('[style]')` will get you all that as inline styles. – Asons May 03 '19 at 04:44
  • 2
    FYI, inline CSS has a better specificity value than your css in media queries. I would also suggest try to remove style attribute as @LGSon mentioned above. Check this out for more information on specificity value https://css-tricks.com/specifics-on-css-specificity/ – Toan Lu May 03 '19 at 04:46
  • And `document.querySelectorAll('[style^="background-color"]')` all that also start with a given property. More here about the attribute selector: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors – Asons May 03 '19 at 04:50
  • This post has a good starting point on how to deal with styles using script: https://stackoverflow.com/a/7894886/2827823 – Asons May 03 '19 at 05:05

1 Answers1

0

remove inline css from body tag, as inline css has high specificity value

and try this, add important in media query as when screen size changes you need lightblue background color

body {
      background-color: yellow;
    }
    @media only screen and (max-width: 600px) {
      body {
        background-color: lightblue;
      }
    }