Languages
[Edit]
EN

CSS - How would you use media queries in a mobile-first approach?

11 points
Created by:
JustMike
3506

Starting from defining styles for mobile devices and later by overriding styles with @media from smaller sizes of screen to bigger (min-width/min-height and max-width/max-height help to select screen size).

1. Main concept

<!doctype html>
<html>
<head>
  <style>

    .class-name {
        /* some styles for mobile device screen */
    }

    /* additionally min-height: [screen_height]px can be used */ 
    @media (min-width: [screen_width]px) {

        /* overridden some styles here e.g. small tablet */ 

        .class-name {
            /* place for styles... */ 
        }
    }

    /* additionally min-height: [bigger_screen_width]px can be used */ 
    @media (min-width: [bigger_screen_width]px) {

        /* overridden some styles here e.g. normal desktop screen  */ 

        .class-name {
            /* place for styles... */ 
        }
    }

    /* additionally min-height: [much_more_bigger_screen_width]px can be used */ 
    @media (min-width: [much_more_bigger_screen_width]px) {

        /* overridden some styles e.g. big desktop screen */ 

        .class-name {
            /* place for styles... */ 
        }
    }

    /* other media cases... */

  </style>
</head>
<body>
  <div class="class-name">
    <!-- Template here... -->
  <div>
</body>
</html>

2. Simple example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    /* for mobile */
    
    .content {
        padding: 10px;
        border: 5px solid orange;
        background: red;
    }

    .content button {
        border: 1px solid gray;
    }

    /* END: for mobile */
    
    @media (min-width: 600px) {
         /* for bigger screen */
      
    	.content {
            background: blue; /* overridden for tablet */
        }

        .content button {
            border: 3px solid red;
        }
    }

   	@media (min-width: 1024px) {
        /* for much more bigger screen */
      
    	.content {
            background: gray; /* overridden for desktop */
        }

        .content button {
            border: 6px solid blue;
        }
    }

  </style>
</head>
<body>
  <div class="content">
	Resize window to see effect...
    <br />
    <button>Click me!</button>
  </div>
</body>
</html>

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.