DEV Community

Cover image for Learn CSS Media Queries by Building Three Projects
joy.does.artworks
joy.does.artworks

Posted on • Originally published at freecodecamp.org

Learn CSS Media Queries by Building Three Projects

Today we're gonna learn how to use CSS Media queries to build responsive websites & practice by doing 3 projects. Let's go πŸ…

Table of Contents -->

Topics to discuss at a glance :

Alt Text

You can watch this tutorial on YouTube as well if you like:

Original Post at Free Code Camp

What are CSS Media Queries?

Alt Text

CSS Media Queries allows us to create Responsive website across all screen sizes ranging from desktop to mobile screen. Therefore, It's a must to learn this topic.

Here's a demo of the magic of Media Queries πŸ‘‡

Alt Text

We'll build that on project 2. Layout is called Card Layout. More Layout Examples here!

How to Set Up the Project

Alt Text

For this project, you need to know little bit of HTML, CSS and know how to work with VS code. Follow along with me ->

  1. Create a folder named "Project-1"
  2. Open VS Code
  3. Create index.html, style.scss & main.js file
  4. install Live Server & SASS Compiler
  5. Run Live Server & SASS Compiler

HTML

On HTML, Write this code inside the body tag πŸ‘‡

 <div class = "container"></div>
Enter fullscreen mode Exit fullscreen mode

we also need to see the exact size of our window. Here's a demo of what I mean πŸ‘‡

Demo

So, write this line below inside the html file, ->

  <div id="size"></div>
Enter fullscreen mode Exit fullscreen mode

SCSS

We'll Use SCSS, not CSS. But..... what is SCSS?

Alt Text

SCSS is a pre-processor of CSS which is more powerful than regular CSS. Using SCSS we can ->

  1. Nest our selectors like a branch of a tree and better manage our code.
  2. Store various values into variables
  3. Use Mixins to stop code repetition & save time

And Much more !

On SCSS, we'll remove our default browser settings, change box-sizing, font-size & font-family, like this πŸ‘‡

*{
  margin : 0px;
  padding : 0px;
  box-sizing : border-box; 

  body{
    font-size : 35px;
    font-family : sans-serif;
  }
}
Enter fullscreen mode Exit fullscreen mode

Don't forget to set height of the .container class. Otherwise we'll fail to achieve our desired results ->

.container{
  height : 100vh;
}
Enter fullscreen mode Exit fullscreen mode

Remember the additional id we wrote in HTML ? We'll style it & position it on our browser here ->

#size {
  position: absolute;

// positioning screen size below our main text
  top : 60%;
  left: 50%;

  transform: translateX(-50%);

  color : red;
  font-size : 35px;
}
Enter fullscreen mode Exit fullscreen mode

JavaScript

We need to update our screen size inside our id every time we resize our window. So, write these codes in main.js file ->


// 'screen' is name πŸ‘‡ of a function
window.onresize = screen;
window.onload = screen;

// Function named 'screen' πŸ‘‡

function screen() {
  Width = window.innerWidth;
  document.getElementById("size").innerHTML 
   = "Width : " + Width + " px" 
}
Enter fullscreen mode Exit fullscreen mode

Download the images for the project

Alt Text

Responsive website also means Responsive Images. We're also going to make images responsive in this project. The images are on my GitHub repository. Here's how to get them:

  1. Visit and copy the link above ☝️
  2. Go to downgit and paste the link you copied
  3. Follow the steps in this video πŸ‘‡

Down Git Steps to follow

And.... we're all set ! Let's Start Coding 😊

Alt Text

The Syntax

The syntax of a Media Query

@media screen and (max-width: 768px){
  .container{
   //Your code's here
  }
}
Enter fullscreen mode Exit fullscreen mode

An illustrated Explanation ->

Alt Text

Let's divide the syntax into 4 section :-

  1. Media Query Declaration
  2. The Media Type
  3. min-width & max-width Function
  4. The Code itself

To understand all 4 section of the syntax, let's start our First Project

Project-1 Video

We'll Build this ☝️ A small project where background-color changes on resizing the window by taking 1 small step at a time. Let's start !

HTML

place some text inside our HTML, like this ->

<div class = "container">

   <div class = "text">
      Hello Screen !
   </div>

</div>
Enter fullscreen mode Exit fullscreen mode

SCSS

Now, we'll store 4 color codes inside variables like this πŸ‘‡

$color-1 : #cdb4db ; // Mobile
$color-2 : #fff1e6 ; // Tablet
$color-3 : #52b788 ; // Laptop
$color-4 : #bee1e6 ; // Desktop
Enter fullscreen mode Exit fullscreen mode

More colors at coolors.co

Now, come at the bottom, target the .container & .text classes. We'll also center our text like thisπŸ‘‡

.container{
//To place text at center

  display : grid;
  place-items : center;

  background-color : $color-1;
  height : 100vh;
}

.text{
 // keep it blank for now
}
Enter fullscreen mode Exit fullscreen mode

So far so good !

Alt Text

1. Media query declaration Rule

Media Queries start with the @media declaration. Main purpose of writing this is to tell the Browser that we have specified a media query. On CSS, write like this πŸ‘‡

@media 
Enter fullscreen mode Exit fullscreen mode

2. The Media Type

This is used to specify the nature of the device we're working with. The 4 values are ->

  • all
  • print
  • screen
  • speech

Purpose of every 4 value at a glance πŸ‘‡

Alt Text

We declare the media type after @media declaration. Like this πŸ‘‡

@media screen
Enter fullscreen mode Exit fullscreen mode

FAQ : Why do we write The "and" operator?

Alt Text

Let's say, we're placing an order at a restaurant, "A burger and a pizza". Notice that the 2 orders are separated by a [and]

Likewise, media type, min-width & max-width functions are basically conditions we are giving to the browser. We don't write "and" operator if we have 1 condition. Like this ->

@media screen {
  .container{
     // Your code here 
  }
}
Enter fullscreen mode Exit fullscreen mode

We write "and" operator if we have 2 conditions. Like this ->

@media screen and (max-width : 768px) {
  .container{
     // Your code here 
  }
}
Enter fullscreen mode Exit fullscreen mode

You can also skip the media type and work with just min-width & max-width. Like this ->

//Targeting screen sizes between 480px & 768px 

@media (min-width : 480px) and (max-width : 768px) {
  .container{
     // Your code here 
  }
}
Enter fullscreen mode Exit fullscreen mode

If you have 3 conditions or more, you can use a comma, like this ->

//Targeting screen sizes between 480px & 768px 

@media screen, (min-width : 480px) and (max-width : 768px) {
  .container{
     // Your code here 
  }
}
Enter fullscreen mode Exit fullscreen mode

3. min-width & max-width Function

Let's discuss the Most important component of a media query, Screen breakpoints.

To be honest, there's no such thing as a standard screen break-point guide due to countless screen sizes on the market. But, for our project, we'll follow The Official Bootstrap 5 screen break-point values

Alt Text

Here's a list of every device screen resolution on CSS-Tricks.

max-width :

Using this function, we are creating a boundary. This will work as long as we are inside the boundary. Here's a sample πŸ‘‡

Our Boundary is 500px

max-width

notice how the light purple color gets Disabled when we hit above 500px.

To recreate this, write these on SCSS

.container{
  background-color: white ;
  height: 100vh;
  display: grid;
  place-items: center;
}
Enter fullscreen mode Exit fullscreen mode

At the bottom, insert the media query, like this πŸ‘‡

@media screen and (max-width : 500px){
  .container{
    background-color: $color-1;
  }
}
Enter fullscreen mode Exit fullscreen mode

min-width :

we are also creating a boundary here. But, This will work if we go outside the boundary. Here's a sample πŸ‘‡

Our Boundary is 500px

Min-width

Notice how the light purple color gets Enabled after we hit above 500px width.

To recreate this, write these on SCSS

.container{
  background-color: white ;
  height: 100vh;
  display: grid;
  place-items: center;
}
Enter fullscreen mode Exit fullscreen mode

At the bottom, insert the media query, like this πŸ‘‡

@media screen and (min-width : 500px){
  .container{
    background-color: $color-1;
  }
}
Enter fullscreen mode Exit fullscreen mode

To sum it up, remember that

  • max-width sets styles inside the set boundary

Alt Text

  • min-width sets styles outside the set boundary

Alt Text

The code itself :

Let's put our project-1 together !

We will have 4 screen breakpoints

  • Mobile -> 576px
  • Tablet -> 768px
  • Laptop -> 992px
  • Desktop -> 1200px

Yes, we are following the official bootstrap 5 screen breakpoints. And each breakpoints will get these colors ->

Alt Text

For 4 device types, we will have 4 Media Queries. Before touching the 4 media queries, first, store the breakpoint values in variables. Like this πŸ‘‡

Note : Don't forget to put the $ sign

$mobile  : 576px;
$tablet  : 768px;
$laptop  : 992px; 
$desktop : 1200px;
Enter fullscreen mode Exit fullscreen mode

And our .container class should look like this πŸ‘‡

.container{
  background-color: white ;
  height: 100vh;
  display: grid;
  place-items: center;
}
Enter fullscreen mode Exit fullscreen mode

We're all 50% done ! Now let's setup the 4 media queries πŸ‘‡

But Wait...

Alt Text

You need to follow a serial while writing the media queries. Start writing from the largest display to the smallest display.

Desktop - 1200px

For the Desktop screen, write these on SCSS πŸ‘‡

// using variable here which is  πŸ‘‡ 1200px
@media screen and (max-width: $desktop){
  .container{
    background-color: $color-4;
  }
}
Enter fullscreen mode Exit fullscreen mode

The Result ->

Alt Text

Laptop - 992px

For the Laptop screen, write these on SCSS πŸ‘‡

// using variable here which is  πŸ‘‡ 992px
@media screen and (max-width: $laptop){
  .container{
    background-color: $color-3;
  }
}
Enter fullscreen mode Exit fullscreen mode

The Result ->

Alt Text

Tablet - 768px

For the tablet screen, write these on SCSS πŸ‘‡

// using variable here which is  πŸ‘‡ 768px
@media screen and (max-width: $tablet){
  .container{
    background-color: $color-2;
  }
}
Enter fullscreen mode Exit fullscreen mode

The Result ->

Alt Text

Mobile - 576px

For the mobile screen, write these on SCSS πŸ‘‡

// using variable here which is  πŸ‘‡ 576px
@media screen and (max-width : $mobile){
  .container{
    background-color: $color-1;
  }
}
Enter fullscreen mode Exit fullscreen mode

The Result ->

Alt Text

Take a Break

Congratulations for Completing Project 1 but, first, take a break. You deserve it !

Alt Text

Let's do some projects using CSS Media Queries

Project-2 Responsive Portfolio

We'll build this, A small responsive WebsiteπŸ‘‡

Desktop View

Alt Text

Mobile View

Alt Text

Okay then, Let's start Coding ! First, let's work with the Desktop View by taking small baby steps

Before Starting

Create a folder named 'images' inside our 'Project-1' Folder. Place all the images you downloaded from my GitHub Repository inside the 'images' folder.

HTML

Step - 1

We'll create 3 sections for our website. Write these Codes inside HTML

<div class="container"> 

    <div class="header"></div>

    <div class="main"></div>

    <div class="footer"></div>

</div>
Enter fullscreen mode Exit fullscreen mode

Step - 2

We'll place the logo & menu items inside the .header div

<div class="header">

      <div class="header__logo">Miya Ruma</div>

      <div class="header__menu">
          <div class="header__menu-1"> Home </div>
          <div class="header__menu-2"> Portfolio </div>
          <div class="header__menu-3"> Contacts </div>
      </div>

  </div>
Enter fullscreen mode Exit fullscreen mode

Step - 3

We'll place the image & text inside the .main div

<div class="main">

     <div class="main__image"></div>

     <div class="main__text">

       <div class="main__text-1">Hello πŸ‘‹</div>

       <div class="main__text-2">I'm <span>Miya Ruma</span></div>

       <div class="main__text-3">A Designer From</div>

       <div class="main__text-4">Tokyo, Japan</div>

     </div>

</div>
Enter fullscreen mode Exit fullscreen mode

Step - 4

We'll place the social media icons inside the .footer div

<div class="footer">

   <div class="footer__instagram">
      <img src="./images/instagram.png" alt="">
   </div>

   <div class="footer__twitter">
      <img src="./images/twitter-sign.png" alt="">
   </div>

    <div class="footer__dribbble">
       <img src="./images/dribbble-logo.png" alt="">
    </div>

    <div class="footer__behance">
       <img src="./images/behance.png" alt="">
    </div>

</div>
Enter fullscreen mode Exit fullscreen mode

SCSS

Alt Text

Step-1

Delete everything inside our SCSS & write these ->

* {
  // placing Margin to left & right
  margin: 0px 5px;

  padding: 0px;
  box-sizing: border-box;

  body {
    font-family: sans-serif;
  }
}
Enter fullscreen mode Exit fullscreen mode

The result so far ->

Alt Text

Step-2

Select All the classes we created in HTML on our stylesheet.

.container{}

.header{}

.main{}

.footer{}
Enter fullscreen mode Exit fullscreen mode

Step-3

Now select all the children of the parent classes.

.header{

  &__logo{}

  &__menu{}
}

.main{

  &__image{}

  &__text{}
}

.footer{

  [class ^="footer__"]{}

}
Enter fullscreen mode Exit fullscreen mode

Note : &__logo nested inside .header is shortcut of .header__logo

Step-4

Define the .container for desktop layout

.container{

// Defining height
  height: 100vh;

  display: flex;

  flex-direction: column;
}
Enter fullscreen mode Exit fullscreen mode

Apply display: flex; to .header & to the menu items so that it behaves like a row, not column

.header{
  display: flex;
  flex-direction: row;

  &__logo{}

  &__menu{
    display: flex;
    flex-direction: row;
  }
}
Enter fullscreen mode Exit fullscreen mode

Divide each section & create borders to see what we are doing

.header{
  display: flex;

// The border & height
  border: 2px solid red;
  height: 10%;

// Other selectors are here

}

.main{

//The border & height
  border: 2px solid black;
  height: 80%;

// Other selectors are here

}

.footer{

// Border & height
  border: 2px solid green;
  height: 10%;

// Other selectors are here
}
Enter fullscreen mode Exit fullscreen mode

The Result ->

Alt Text

Step-5

Let's complete styling our .header section using flex-box properties & appropriate font-size

.header {
// height
  height: 10%;

  display: flex;
// Aligning logo & menu at center
  align-items: center;

// space between logo & menu
  justify-content: space-between;

  &__logo {
    font-size: 4vw;
  }

  &__menu {
    display: flex;
    font-size: 2.5vw;

// to put gap between menu items
    gap: 15px;
  }
}
Enter fullscreen mode Exit fullscreen mode

The result ->

Alt Text

Step-6

Alt Text

Let's add the image inside .main section & create a partition for image & text.

.main {
  // image & text will act like a row
  display: flex;
  flex-direction: row;

  //The border & height
  border: 2px solid black;
  height: 80%;

  &__image {
    //Adding the image
    background-image: url("./images/Portrait.png");
    // will cover half of screen width
    width: 50%;
  }

  &__text {
    // will cover half of screen width
    width: 50%;
  }
}
Enter fullscreen mode Exit fullscreen mode

The ugly result so far, but don't lose hope !

Alt Text

Step-7 - The image

Style the image to be responsive ->

.main{
  &__image{
  //make image fluid
    background-size: contain;

  // stop image repetition
    background-repeat: no-repeat;

  // position the image
    background-position: left center;
  }
}
Enter fullscreen mode Exit fullscreen mode

The result so far ->

Alt Text

The image is responsive from 4k till your smart watch screen. Don't believe me? Open chrome developer tools & test it yourself and see.

4k test

Step-8 - The text

Let's style our text now. Bring it to the exact center

.main{

  &__text {
    // will cover half of screen width
    width: 50%;
    display: flex;
    flex-direction: column;

// To bring it at the center 
    justify-content: center;
    align-items: center;
  }

// To color The name 
  span{
    color: red;
  }

}
Enter fullscreen mode Exit fullscreen mode
.main{


  &__text{

// To add gaps between texts vertically
    gap: 15px;

// font size for "hello"
    &-1{
      font-size: 10vw;
    }

// font size for other texts
    &-2,&-3,&-4{
      font-size: 5vw;

    }

  }
}

Enter fullscreen mode Exit fullscreen mode

The result ->

Alt Text

  • Upto this point, you can remove all the borders we placed inside our header, main & footer classes

Step-9 : The footer Section

First, resize the images like this ->

.footer{
  [class^="footer__"] {
    img {
      width: 5.3vw;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Then, position the images to our desired place, with some gap between the icons ->

.footer{
  display: flex;
  flex-direction: row;

// To align icons along x-axis
  align-items: center;
// placing image to the right side
  justify-content: flex-end;
// Gap between icons
  gap: 20px;

// margin to right side of icons 
  margin-right: 10%;
}
Enter fullscreen mode Exit fullscreen mode

The result, without the guides ->

Alt Text

Step-10 : The mobile Layout

Almost there !

Alt Text

Create a media query at 650px mark & style the .header class like this ->

@media (max-width: 650px) {

  .header {

// To place logo at center
    justify-content: center;

    &__logo {
      font-size: 40px;
    }
//hiding the menu on mobile device
    &__menu {
      display: none;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Step-11

Now, place the .main section at the exact center ->

@media (max-width: 650px){
// styles of header section of step-10...

// main section here 
  .main {
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
Enter fullscreen mode Exit fullscreen mode

step-12 :

Style the image & text for mobile layout. Like this ->

@media (max-width: 650px){

 .main {
   &__image {
// Image size 
      height: 200px;
      width: 200px;
      background-size: 100%;

// To have rounded image 
      border-radius: 100%;
      background-position: center;
    }

// Styles for the text ->
    &__text {
      width: 100%;

      &-1 {
        display: none;
      }
      &-2, &-3, &-4 {
        font-size: 30px;
      }
    }
}

Enter fullscreen mode Exit fullscreen mode

Step-13

The last step, Let's style the footer section for the mobile layout ->

@media (max-width: 650px){
  .footer {
// placing icons along the X-axis
    justify-content: center;
    margin: 0px;

    [class^="footer__"] {

// Resizing images for mobile layout
      img {
        width: 45px;
        height: 45px;
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

The result ->

Alt Text

Take a break

Good job so far ! Take a break😊

Alt Text

Project-3 The Card Layout

In Project 3, We'll build this ->

Alt Text

Let's start !

SCSS

On your stylesheet, delete everything, but don't delete the styles of #size. And write these ->

* {
  margin: 0px;
  padding: 0px 10px;
  box-sizing: border-box;

  body {
    font-family: sans-serif;
    font-size: 55px;
  }
}

#size{
  position: absolute;
// Positioning the text
  top: 60%;
  left: 50%;
  transform: translateX(-50%);
// color & size of text
  color: red;
  font-size: 40px;
}

Enter fullscreen mode Exit fullscreen mode

HTML

You're HTML should look like this inside the body tags πŸ‘‡

<div class="container"> 
   // We'll place code here
</div>

// This will show our window width Live 
<div id="size"></div>
Enter fullscreen mode Exit fullscreen mode

Now, create 3 classes with class names .row-* like this πŸ‘‡ inside .container

<div class="container"> 

   <div class="row-1">
   </div>

   <div class="row-2">
   </div>

   <div class="row-3">
   </div>
</div>
Enter fullscreen mode Exit fullscreen mode

Each row will have 3 boxes with class names .box-* like this πŸ‘‡
And yes, Insert Letters inside the boxes

<div class="container"> 

   <div class="row-1">
       <div class="box-1">A</div>
       <div class="box-2">B</div>
       <div class="box-3">C</div>
   </div>

   <div class="row-2">
       <div class="box-4">D</div>
       <div class="box-5">E</div>
       <div class="box-6">F</div>
   </div>

   <div class="row-3">
       <div class="box-7">G</div>
       <div class="box-8">H</div>
       <div class="box-9">I</div>
   </div>
</div>
Enter fullscreen mode Exit fullscreen mode

We're done with the HTML part and the result should look like this πŸ‘‡

Alt Text

SCSS

Follow these small baby steps one by one πŸ‘‡

Step-1

To select & style all the boxes & rows together, we do these on CSS πŸ‘‡

.container{
  // styles here 
}

[class ^="row-"]{
  // Styles applied on all rows
}

[class ^="box-"]{
  // Styles applied on all boxes
}
Enter fullscreen mode Exit fullscreen mode

Step-2

Boxes should behave like a row. Write these ->

[class ^="row-"]{
  display: flex;
  flex-direction: row;
}
Enter fullscreen mode Exit fullscreen mode

The result πŸ‘‡

Alt Text

Step-3

Expand the boxes across the width & height & place the letters at the center. Follow me ->

[class ^="box-"]{

  background-color: #c4c4c4;
  border: 2px solid black;

// Defining the size of the boxes 
  width : (100%)/3;
  height: (100vh)/3;

// Place letter at the center
  display: grid;
  place-items: center;
}
Enter fullscreen mode Exit fullscreen mode

The Result ->

Alt Text

Step-4

create gap among the rows. Follow me ->

.container{
  display: flex;
  flex-direction: column;
  height: 100vh;

// Creating gap between rows 
  gap: 30px;
}
Enter fullscreen mode Exit fullscreen mode

Now to create gap between Boxes ->

[class ^="row-"]{
  display: flex;
  flex-direction: row;

// Creating gap between boxes
  gap : 30px;
}
Enter fullscreen mode Exit fullscreen mode

The Result ->

Alt Text

Step-5 -> The mobile Layout

Create Media query which will be applied at 650px mark

@media (max-width: 650px){
  // We'll write code here
}
Enter fullscreen mode Exit fullscreen mode

Change orientation of the boxes on the mobile screen from row to column, and stretch the boxes to 100% of the width ->

@media (max-width: 650px){

//Change orientation
  [class ^="row-"]{
    flex-direction: column;
  }

// Change width of boxes
  [class ^="box-"]{
    width: 100%;
  }
}
Enter fullscreen mode Exit fullscreen mode

The Final Result ->

Alt Text

By the way, Project 2 is a part of this article of mine. If you're interested to learn & practice both about flexbox & media query, then go for it !

Conclusion

Here's Your Medal For reading till the end ❀️

Suggestions & Criticisms Are Highly Appreciated ❀️

Alt Text

Credits

Oldest comments (3)

Collapse
 
afif profile image
Temani Afif

better contact the support to get back your old account. If you own the email of the other account you can recover it easily (I guess ..)

Collapse
 
artworks_joy profile image
joy.does.artworks

Let's hope for the best :")

Collapse
 
jpchreim profile image
Jean Pierre Chreim

Great Job man, I definetly needed it !

Some comments may only be visible to logged-in visitors. Sign in to view all comments.