-1
<div style="margin: 4rem 0  4rem 0;">
<h1>Some Content</h1>
</div>

I'm trying to write a media query to ignore this rule.. style="margin: 4rem 0 4rem 0;" at a certain view port. Besides giving the div a class or id and targeting the class or id in the media query is there a way to target just this specific div and ignore the style rule? I know its not a big deal to just add a class but i'm just curious if you can do it without adding a class or id.

  • 1
    Do read up on **CSS specificity**. It is impractical (should not be doing so either) to override these rules directly defined inline using the `style=""` attribute, unless using `!important`. You need to define these default rules somewhere else, i.e. in the ` – Daniel Cheung Feb 28 '21 at 18:34

3 Answers3

0

you can apply the media query to a div. Depending on the structure of your html dom you can target children and siblings using css. Narrow the width of your browser window and you should see the div's background change to light blue. And yes you can even change the margin but you will need to use !important.

@media only screen and (max-width: 600px) {
  div {
    background-color: lightblue;
    margin:0!important;
  }
}
<div style="margin: 4rem 0  4rem 0;">
<h1>Some Content</h1>
</div>

 body div:first-child
   {
      color:red;
   }
<html>
 <head>
  
 </head>
 <body>
  <div>I should be red.</div>
  <div>This is not red.</div>
 </body>
</html>
DCR
  • 14,737
  • 12
  • 52
  • 115
  • Wont that apply the margin: 0 !important; to all the div elements in the html and not apply it to just that specific div? – Halp_am_stuck1 Feb 28 '21 at 18:50
  • yes. but it's just an example and shows the use of !important. That's why I said it depends on the structure of your html. see second example in my updated snippet – DCR Feb 28 '21 at 18:59
0

I think you can't re-write the margin style. To do that you should create a class and then it will work.

<div class="div">
    <h1>Some Content</h1>
</div>

<style>
    div {
        margin: 4rem 0 4rem 0;
    }
    
    @media screen and (max-width: 1000px) {
        .div {
            margin: 0 0 0 0;
            color: red;
        }
    }
</style>
NickNterm
  • 94
  • 4
0

If you can not add class or id to specify selector, you still may use selector by attributes.

in your case it will look like this:

@media screen and (max-width: 1000px) {
  div[style="margin: 4rem 0  4rem 0;"] {
    ...
  }
}
Vlad
  • 459
  • 4
  • 8