The @media At-rules in CSS



The CSS @media rule is used to specify different styles for different media types (such as print, screen, all, etc.) in a single style sheet. It is usually followed by a comma-separated list of media types and the CSS declarations block containing the styles rules for target media.

Syntax

Following is the syntax −

@media not | only mediatype and (expressions) {
   CSS-Code;
}

Example

Let’s see an example of CSS @media rule −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
   box-sizing: border-box;
}
.col {
   float: left;
   width: 20%;
   padding: 40px;
}
body {
   background-color: lemonchiffon;
   margin: 20px;
}
@media screen and (max-width: 850px) {
   .col {
      width: 50%;
   }
   body {
      background-color: mediumseagreen;
   }
}
@media screen and (max-width: 550px) {
   .col {
      width: 100%;
   }
   body {
      background-color: powderblue;
   }
}
</style>
</head>
<body>
<div class="row">
<div class="col" style="background-color:#373;"> </div>
<div class="col" style="background-color:#363;"> </div>
<div class="col" style="background-color:#353;"> </div>
<div class="col" style="background-color:#343;"> </div>
<div class="col" style="background-color:#333;"> </div>
</div>
</body>
</html>

Output

This will produce the following output −

When screen size is above 850px −

When screen size is between 550px and 850px −

When screen size is below 550px −

Example

Let’s see another example for CSS @media rule −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
p {
   background-origin: content-box;
   background-repeat: no-repeat;
   background-size: cover;
   box-shadow: 0 0 3px black;
   padding: 20px;
   background-origin: border-box;
}
@media screen and (max-width: 900px) {
   p{
      background: url("https://www.tutorialspoint.com/swing/images/swing.jpg");
      color: #c303c3;
   }
}
@media screen and (max-width: 500px) {
   p {
      color: black;
      background: url("https://www.tutorialspoint.com/cplusplus/images/cplusplus.jpg");
   }
}
</style>
</head>
<body>
<p>This is demo text. This is demo text. This is demo text. This is demo text. 
This is demo text. This is demo text. This is demo text. This is demo text. 
This is demo text. This is demo text. This is demo text. This is demo text. 
This is demo text. This is demo text. This is demo text. This is demo text. 
This is demo text. This is demo text. This is demo text. This is demo text. 
This is demo text. </p>
</body>
</html>

Output

This will produce the following output −

When screen size is above 500px −

When screen size is below 500px −


Advertisements