Media queries

Media queries are a tool used in web development to apply different styles to a web page based on the size of the device it is being viewed on. Essentially, media queries allow developers to create a responsive design that adapts to the screen size and resolution of the device accessing the website.

Here's an example:

/* Set default styles */
body {
  font-size: 16px;
  background-color: white;

/* Apply styles for screens 768px wide or narrower */
@media (max-width: 768px) {
  body {
    font-size: 14px;
    background-color: lightgray;

In this example, the default font size for the body element is 16 pixels, and the background color is white. However, when the screen width is 768 pixels or narrower (such as on a smartphone), the font size will be reduced to 14 pixels, and the background color will be changed to light gray. This ensures that the website remains readable and visually appealing, even on smaller screens.

Media queries can also be used to adjust other style properties, such as the layout, margins, padding, and font sizes of various elements. Here are a few more examples:

/* Apply styles for screens 480px wide or narrower */
@media (max-width: 480px) {
  .header {
    font-size: 20px;
    padding: 10px;
    text-align: center;
  .main {
    margin: 0;

/* Apply styles for screens 1024px wide or wider */
@media (min-width: 1024px) {
  .sidebar {
    float: right;
    width: 25%;
    margin-left: 2%;
    margin-right: 0;
  .main {
    float: left;
    width: 70%;
    margin-right: 2%;
    margin-left: 0;

In the first example, when the screen is 480 pixels or narrower, the font size of the header will be increased to 20 pixels, padding will be added to the header and the text will be centered. The main section's margins will be removed.

In the second example, when the screen is 1024 pixels or wider, the sidebar and main content will be arranged in a two-column layout. The sidebar will be floated to the right and given a width of 25%, while the main content will be floated to the left and given a width of 70%. Margins will be adjusted to ensure that the columns are spaced apart properly.

Overall, media queries allow developers to create websites that look great on a wide range of devices, from smartphones to desktop computers. By adjusting the layout and style of various elements based on the size of the screen, web developers can ensure that users have a positive experience regardless of the device they are using.

Was this page helpful?