Categories: Development

Responsive CSS style based on screen width with @media

Using @media in CSS allows you to specify styles for a certain viewpoint (width/height). This helps with creating responsive designs if you’re not using a framework such as Bulma or Bootstrap.

@media has a few parameters of which you can read here the most popular one however is max-width.

With this CSS:

@media only screen and (max-width: 750px) {
  body {
    background: green;
  }
}

When the viewing screen is 750px wide or less the background will be green

@media only screen and (max-width: 750px) {
  body {
    background: green;
  }
}

@media only screen and (max-width: 500px) {
  body {
    background: red;
  }
}

From a screen width of 750px through to 501px the background will be green, once it gets to 500px it will change to red.

Of course you can put any CSS in the @media statement, but background color changing is just to have an easy observation for this post.

The above video is from this CodePen of the @media query showing the max-width parameter.

As the screen gets smaller in width the @media rule comes into effect.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago