CSS: @media query (responsive design)

By Xah Lee. Date: . Last updated: .

What is Media Query

Media Query applies a set of CSS rules only when a condition is satisfied. Most often used to set CSS depending on user's screen size.

Syntax:

@media all and conditionalExpression { cssRules }

Media Queries is new in 2012 (CSS 3).

Example. Screen Less Than

If viewport width is less than 600px

@media all and (max-width: 600px) {
 body {
  background-color: yellow;
 }
}

Once you set the rule, you can drag to change window size to see its effect in realtime.

Example. Screen Greater Than

If viewport width is greater than 1000px

@media all and (min-width: 1000px) {
 body {
  background-color: cyan;
 }
}

Example. Screen Size Between

If viewport width is between 1000px and 1500px.

@media all and (min-width: 1000px) and (max-width: 1500px) {
 body {
  background-color: cyan;
 }
}

what is responsive design

Responsive Design means using Media Query to design site such that different screen size results in different design. (desktop big display, or cell phone tiny display) .

example. show nav panel to left if large screen, else at or bottom

@media all and (min-width: 701px) {
 /* show nav panel at left if screen is large */

 main {
  margin-left: var(--xpage-left-magin);
 }
 footer {
  margin-left: var(--xpage-left-magin);
 }
 .lpanelxl {
  position: absolute;
  top: var(--xpage-top-margin);
  left: 2px;
 }

 /* show 2 columns */
 .x2col {
  column-count: 2;
 }
}

example. show nav panel to left if large screen, else at or bottom

@media all and (max-width: 500px) {
 /* mobile phone screen */

 pre, code, h1, s, a, li {
  overflow-wrap: anywhere;
 }

 table {
  display: block;
 }

 table caption {
  display: inline-block;
 }

 table tr {
  display: list-item;
  border: none;
  border-top: solid 2px grey;
  margin: 0.5rem;
 }

 table th {
  display: inline-block;
  border: solid thin gray;
  margin-right: 0.2rem;
  margin: 0.5rem;
  border-radius: 0.5rem;
 }

 table td {
  display: inline-block;
  border: solid thin gray;
  margin: 0.5ex;
  border-radius: 0.5rem;
 }
}

CSS. Media Query

CSS. misc, advanced