Search code examples
cssreactjsresponsive-designmedia-queriesstyled-components

Why are my media queries not applying correctly?


Only the last declared media query is being applied, regardless of the screen size. In the example component below, the color is always green, even when the screen width is 320px.

Breakpoints:

const size = {
    mobileM: '400px',
    mobileL: '480px',
    tablet: '760px',
    laptop: '1280px', 
    desktopM: '1530px',
    desktopL: '1920px',
};

export const devices = {
    mobileM: `(min-width: ${size.mobileM})`,
    mobileL: `(min-width: ${size.mobileL})`,
    tablet: `(min-width: ${size.tablet})`,
    laptop: `(min-width: ${size.laptop})`,
    desktopM: `(min-width: ${size.desktopM})`,
    desktopL: `(min-width: ${size.desktopL})`
};

Example component:

import React from 'react'
import styled from 'styled-components'
import { devices } from '../utils/breakpoints';

function Welcome() {
  return (<>
    <HeaderMessage>Welcome</HeaderMessage>
    <BodyText>
      This questionnaire is used to help us understand your business goals and needs and guide us to create the best solution for you. 
    </BodyText>
    
    <BodyText>
      Please be as specific as possible in your answers as it will give us the most insight and enable us to help you best. 
    </BodyText>
    
    <BodyText>
      Use the back arrow in the top left corner at any time to navigate to a previous page to amend your answers.
    </BodyText>

  </>)
}

// font-family: 'Krona One', sans-serif;
// font-family: 'Montserrat', sans-serif;

const HeaderMessage = styled.h1`
  color: #BA3D9C;
  text-transform: uppercase;
  font-family: 'Krona One', sans-serif;
  font-size: 6rem;
  letter-spacing: .5rem;
  margin-top: -13vw;
  margin-bottom: 5rem;
  @media ${devices.mobileM} {
    margin-top: 0;
    color: turquoise;
  }
  
  @media ${devices.mobileL} {
    color: blue;
    font-size: 5rem;
    margin-top: 1rem;
    margin-bottom: 2rem;
  }

  @media ${devices.tablet}{
    color: green;
    font-size: 4rem;
    margin-top: 1rem;
  }
`;

In the above component, the color is always green, even when the screen width is 320px.


Solution

  • The reason Chrome was ignoring my media queries but Firefox wasn't was because I was missing the viewport meta tag in the head of my HTML file <meta name="viewport" content="width=device-width,initial-scale=1">. Without this, Chrome was ignoring my media queries.