Applying CSS Conditionally

Last Updated On Thursday 2nd Jun 2022
  • Conditional CSS refers to CSS rules that are applied when a condition is met.
  • A condition maybe a CSS property and value combination, as with the @supports rule.
  • A condition may test for a browser window condition such as width, as with the @media rule.

Media Queries and @media

  • The @media rule is a long-standing feature of CSS.
  • Its syntax was initially defined by the CSS 2 specification back in 1998.

Media Query Syntax

as opposed to being printed:

	@media screen {
   /* Styles go here */
}
	
  • CSS style rules are nested within this @media rule set.
  • They’ll only apply when the document is displayed on a screen.
	@media screen {
   body {
     font-size: 20px;
   }
}
	

Media features the capabilities of the device or conditions of the viewport.

	@media ( width: 480px ) {
  nav li {
    display: inline-block;
  }
}
	

Min and Max Prefixes

  • A more flexible media query might test for a minimum or maximum viewport width.
  • We can apply styles when the viewport is at least this wide, and no more than that wide
	@media ( max-width: 480px ) {
   nav li {
     display: block;
   }
}
	
	@media ( min-width: 481px ) and ( max-width: 1600px ) {
   nav ul {
     display: flex;
   }
}
	
  • If both conditions are true, that is, the viewport width is at least 480px, but not greater than 1600px our styles will apply.
	@media screen and ( hover: on-demand ) {
   input[type=checkbox] + label {
     padding: .5em;
   }
}
	

Nesting @media Rules

	@media screen {
    @media ( min-width: 320px) {
        img {
            display: block;
            width: 100%;
            height: auto;
        }
    }
    @media ( min-width: 640px) {
        img {
            display: inline-block;
            max-width: 300px;
        }
    }
}
	
  • A current common practice when using media queries is to set min-width and max-width breakpoints based on popular device sizes.
  • A breakpoint is the width or height that triggers a media query.
	@media screen and ( max-width: 320px) {}

@media screen ( min-width: 320px) and ( max-width: 480px) {}

@media screen ( min-width: 481px) and ( max-width: 768px) {}

@media screen ( min-width: 769px) {}
	

Using Media Queries with JavaScript

  • Media queries also have a JavaScript API, better known as matchMedia().
  • The matchMedia() method is a property of the window object.
  • You Can use it window.matchMedia() or just matchMedia().
	var isWideScreen = matchMedia("(min-width: 45em)");
console.log(isWideScreen.matches); // true || false
	

Selector Support with selector()

	@supports selector( :blank ) {
   input:not(:blank):invalid {
     background: pink;
   }
}
	
  • Both @media and @supports are powerful and flexible.