skip to Main Content

I have an HTML/CSS/JS project.

In my <head> tag, I have this viewport <meta> tag:

    <meta name="viewport" content="width=device-width, initial-scale=1" />

In my CSS file, I have two media queries that are firing at values that are unexpected. I have defined the media queries with max-width, yet the changes in the UI are happening at different viewports, as described below in the comments:

/* actually happening between 320px and 561px */
@media only screen and (max-width: 700px) {
  .sidebar {
    border: 1px solid orange;
    width: 100%;
    height: auto;
    position: relative;
    display: flex;
  }

  main {
    margin-left: 0;
  }
}

/* actually happening when the screen is <= 320px */
@media only screen and (max-width: 400px) {
  .sidebar {
    border: 1px solid green;
    display: flex;
    flex-direction: column;
    text-align: center;
  }
}

Does anyone know why this could be happening and how I could make the changes happen where I would like them (at max-width: 700px and max-width: 400px, respectively )?

2

Answers


  1. Remove initial-scale=1:

    <meta name="viewport" content="width=device-width" />
    

    when you do so, you allow the browser to handle the scaling,
    which might result in a more accurate interpretation of your media queries.

    Use min-width instead of max-width

    /* Change at or above 700px */
    @media only screen and (min-width: 701px) {
      /* Styles */
    }
    
    /* Change at or above 400px */
    @media only screen and (min-width: 401px) {
      /* Styles */
    }
    

    it’s a lot easier when you think of max-width and min-width as "less than" and "greater than".

    Hope you find this helpfull!

    Login or Signup to reply.
  2. Also you can be more precise with using "new CSS media query range syntax" :
    https://css-tricks.com/the-new-css-media-query-range-syntax/

    Like that :

    @media (400px <= width <= 700px) {
      .sidebar {
        border: 1px solid orange;
        width: 100%;
        height: auto;
        position: relative;
        display: flex;
      }
    
      main {
        margin-left: 0;
      }
    }
    
    @media (0px <= width <= 400px) {
      .sidebar {
        border: 1px solid green;
        display: flex;
        flex-direction: column;
        text-align: center;
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search