skip to Main Content

I need my html file work on html email, so I set inline CSS for my code and I still need it can dynamic changes when device is mobile or desktop.

Here is some code what I try:

<html lang="en">
<style>
  @media (min-width: 1024px) {
    .separate {
      width: 50%;
    }
  }
</style>
  <body>
    <div 
      class="separate-container" 
      style="display: flex; justify-content: center; align-items: center;"
    >
      <div 
        class="separate" 
        style="width: 96%; height: 1px; background-color: #757575; opacity: 20%;}"
      >
      </div>
    </div>
  </body>
</html>

I want the <div class="separate" /> width is 96% for mobile, 50% for desktop.
But in the result my separate is always 96%.

Is it possible dynamic changes when using inline CSS ?

3

Answers


  1. Inline style won’t help you switch the styles with conditions

    because you have applied class and also specifically applied in style tag, instead do this

    <html lang="en">
    <style>
      .separate {
          width: 96%
      }
    
      @media (min-width: 1024px) {
        .separate {
          width: 50%;
        }
      }
    </style>
      <body>
        <div 
          class="separate-container" 
          style="display: flex; justify-content: center; align-items: center;"
        >
          <div 
            class="separate" 
            style="height: 1px; background-color: #757575; opacity: 20%;}">
          </div>
        </div>
      </body>
    </html>
    

    removed width from inline style and applied in class. Now your css can switch between media query : 50% and the default one : 96 %.

    Login or Signup to reply.
  2. CSS works with specificity. In your case, inline will always be prevalent over everything.

    I can’t think of a way to make it work without using two media queries or using !important like this:

    <style>
      @media (min-width: 1024px) {
        .separate {
          width: 50% !important; // This will override any `style`
        }
      }
    </style>
    
    Login or Signup to reply.
  3. The documentation clearly states:

    Inline styles […] always overwrite any normal styles in author stylesheets. […] The only way to override inline styles is by using !important.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search