Home Snippets Projects Donate

Get Snippets For:

   Java    HTML/CSS JavaScript

Media Queries

Code Description:

Media Queries allow you to change CSS styles based on the size of your device's screen or the browser's window size. You can set breakpoints to update styles at certain pixel widths. Typically, the styles should change based on the screen size getting larger as shown in the Growing Media Query Syntax example. This is to support the "Mobile First" initiative.

Growing Media Query Syntax:

/* If the size of the screen exceeds 600 pixels in width or more, all paragraphs will have their background color set to yellow. */
@media only screen and (min-width: 600px) {
  p {
    background-color: yellow;
  }
}

/* If the size of the screen exceeds 900 pixels in width or more, all paragraphs will have their background color set to orange. */
@media only screen and (min-width: 900px) {
  p {
    background-color: orange;
  }
}

Shrinking Media Query Syntax:

/* If the size of the screen becomes 900 pixels in width or smaller, all paragraphs will have their background color set to yellow. */
@media only screen and (max-width: 900px) {
  p {
    background-color: yellow;
  }
}

/* If the size of the screen becomes 600 pixels in width or smaller, all paragraphs will have their background color set to orange. */
@media only screen and (max-width: 600px) {
  p {
    background-color: orange;
  }
}
<!DOCTYPE html>
<html>
    <head>
        <title>Media Query Example</title>
	   
	<style>
	   
	/* If the size of the screen exceeds 600 pixels in width or more, all paragraphs will have their background color set to yellow. */
        @media only screen and (min-width: 600px) {
           p {
              background-color: yellow;
           }
        }

        /* If the size of the screen exceeds 900 pixels in width or more, all paragraphs will have their background color set to orange. */
        @media only screen and (min-width: 900px) {
           p {
              background-color: orange;
           }
        }
	   
        </style>
	   
    </head>
 
    <body>
	<p>Paragraph 1 Example Text...</p>
	<p>Paragraph 2 Example Text...</p>
	<p>Paragraph 3 Example Text...</p>
    </body>
</html>

How to Run This Code:

Simply paste this code into a plain text file with the ".html" extension and save it. You will then be able to open it in the web browser of your choice. Experiment with resizing your browser window.

Related Links: