Command Shift

Media Queries

Think about how much we've grown, tech-wise, in the past 20 years. We have more and more devices with a panoply of screen sizes. How many times do you actually find yourself accessing websites on your phone, or tablet, instead of a fully fleged computer?

It's with this in mind that nowadays we take a mobile first approach, where we design and build applications following a rule of progressive enhancement. This fancy statement translates into building thinking of the smallest of the devices first and then expanding it to wider screens.

In all fairness, we do all of this because, as also users, we crave from that amazing and simple User eXperience!

There's a couple of things we can do to achieve this, where experience and exposure will play a massive role, but the primary one is the use of media queries.

Media queries are expressions that evaluate to either true or false. Take a look at this snippet:

.box {
	height: 100px;
}
 
@media screen and (min-width: 768px) {
	.box {
		height: 500px;
	}
}

The syntax for a media query is always the same. You use the keyword @media followed by the type of the media you'll be checking (can be all, print, screen, speech) and then your condition.

In this example, we have an element with a class of box, which has its height set to 100px. We then define a media query that checks the width of the page. Once it reaches a minimum of 768px, it changes the height of the box to 500px. Simple as that.

You should set your media queries at the end of the CSS file so it overrides all of the previously set properties, as long as the condition evaluates to true.


Practice:

Exercise - Media Queries

You'll find a codepen that was built with a mobile first approach. For smaller devices, the navigation elements are stack on top of each other. However, for wider screens we would like to have them justified to the right, as in the previous exercise. So, the goal is for you to write a media query with the needed properties to achieve this goal.

Note: We would like these changes to be applied right from the tablet's size, at 768px width.

On this page