Search code examples
htmlcsshtml-email

How to make @media working for inline CSS?


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 ?


Solution

  • 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 %.