coryhouse/reactjsconsulting

Media Queries

coryhouse opened this issue · 0 comments

Why Media queries? Include some CSS when some condition is true.

Example:

@media only screen and (max-width: 600px) {
  body {
    background-color: lightblue;
  }
}

Make background blue when in landscape mode (width > height)

@media only screen and (orientation: landscape) {
  body {
    background-color: lightblue;
  }
}

Show content on > 600px screen (this assumes hidden by default in separate CSS):

@media only screen and (min-width: 600px) {
  div.example {
    display: block;
  }
}

Media Types

  • all - default
  • screen - Computer screens, tablets, smart-phones
  • print - applies when printing hit print here for Example.
  • speech - For screen readers
<link rel="stylesheet" media="screen" href="styles.css"/>
<link rel="stylesheet" media="print" href="print-styles.css"/>
@media screen {
  body {
    color: white;
    background-color: black;
  }
}

@media print {
  body {
    color: white;
    background-color: black;
  }
}

Can even apply a stylesheet for specific screens:

<link rel="stylesheet" media="screen and (max-width: 600px)" href="smallscreen.css">

For multiple options, a comma operates as an OR.

Example: When the width is between 600px and 900px OR above 1100px - change the appearance of

@media screen and (max-width: 900px) and (min-width: 600px), (min-width: 1100px) {
  div.example {
    font-size: 50px;
    padding: 50px;
    border: 8px solid black;
    background: yellow;
  }
}

Media Features

Useful for applying media query in specific circumstances such as viewport width/height, orientation, and prefers-* rules that convey the user's preferences. Full list on MDN.

The prefers-* settings use OS level settings. Examples: color-scheme and reduced-motion.

@media (prefers-color-scheme: dark) {
  body {
    background-color: black;
    color: white;
  }
}

Run JS based on media queries

Can use window.matchMedia() to run JS that matches a media query. Also consider MediaQueryList, though not as broadly supported.

  • Normalizing cutoff points
    • Built into Bootstrap
  • Setting meta tags for viewports 

React

react-responsive - Hook for declarative breakpoints.