Is It Possible to Use the CSS @media Rule Inline

Solution with the internal style

It is not possible to use CSS @media rules and media queries in the inline style attribute as it can only contain property: value pairs. According to the W3 specification, the style attribute’s value should match the syntax of contents of a CSS declaration block.

The only possible way of applying styles to an element in certain media is by using a separate rule in the stylesheet.

So, the common use of @media rules (in the internal style) looks like the following.

Example of applying @media rules in the internal style:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      body {
        background-color: #1c87c9;
      }
      @media screen and (min-width: 200px) {
        body {
          background-color: #51d675;
        }
      }
      @media screen and (min-width: 600px) {
        body {
          background-color: #ccc;
        }
      }
      @media screen and (max-width: 800px) and (min-width: 500px),
      (min-width: 1000px) {
        div.box {
          font-size: 40px;
          padding: 50px;
          border: 6px solid #000;
          background: #eee;
        }
      }
    </style>
  </head>
  <body>
    <p>
      To see the effect, resize the browser window.
    </p>
    <p>
      Change the appearance of the DIV on different screen sizes.
    </p>
    <div class="box">DIV</div>
  </body>
</html>

Result

To see the effect, resize the browser window.

Change the appearance of the DIV on different screen sizes.

DIV

Example of using @media rules in the internal style:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      @media screen and (max-width: 767px) {
        .content {
          background-color: lightblue;
          padding: 30px;
        }
      }
      @media screen and (min-width: 768px) {
        .content {
          background-color: pink;
          padding: 10px;
        }
      }
      @media screen and (min-width: 800px) {
        .content {
          background-color: lightgreen;
          color: white;
          padding: 50px;
        }
      }
    </style>
  </head>
  <body>
    <div class="content">
      <h2>Resize the browser to see the effect.</h2>
      <p>
        CSS is a rule-based language, which means that you define
        rules specifying groups of styles applying to particular
        elements or groups of elements on the web page.
      </p>
    </div>
  </body>
</html>

Do you find this helpful?

Related articles