Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • CSS Tutorial
  • CSS Exercises
  • CSS Interview Questions
  • CSS Selectors
  • CSS Properties
  • CSS Functions
  • CSS Examples
  • CSS Cheat Sheet
  • CSS Templates
  • CSS Frameworks
  • Bootstrap
  • Tailwind
  • CSS Formatter
Open In App
Next Article:
How to skip a test in Cypress conditionally ?
Next article icon

How to load css resources conditionally ?

Last Updated : 29 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In the world of web development, CSS plays a crucial role in styling HTML code. Typically, the CSS code is linked in the head tag of an HTML document, allowing developers to easily apply styles to the content of a web page. However, there may be times when the desired styling is dependent on specific conditions, such as the size of the viewport or the type of device being used to access the website.

In these situations, it becomes important to have the ability to conditionally alter CSS styles based on these conditions. This is where the power of CSS conditional styling comes into play. In this article, we will delve into various approaches to conditionally changing CSS styles, giving you the tools and knowledge needed to take your web development skills to the next level.

Here are some approaches to using CSS conditionally:

  1.  Using Media Queries.
  2.  Using Media Attribute in “style” or “link” tags.
  3.  Loading Printer-specific CSS.
  4.  Loading CSS based on Dark/Light Mode.

Approach 1: Using Media Queries:

Media queries are a feature of CSS (Cascading Style Sheets) that enable you to specify different styles for a webpage based on the dimensions of the viewport or the device being used. This is useful for creating responsive designs, which are websites that can adapt to different screen sizes and device types.

In a media query, the media type specifies the type of media that the styles should be applied to, and the expressions check for the dimensions of the viewport or the device being used. If the media type and expressions match the characteristics of the device, the styles specified in the media query will be applied.

You can refer to Media Query to learn more about it.

Example:

HTML
<!DOCTYPE html> <html>  <head>     <title>Load CSS conditionally</title>     <style>         body {             background-color: black;             color: white;         }          @media screen and (max-width: 900px) {             body {                 background-color: lightgrey;                 color: black;             }         }          h2 {             color: green;         }     </style> </head>  <body>     <h2>Welcome To GFG</h2>     <p>Now, we are going to learn some            stuff regarding CSS.</p> </body>  </html> 

Output:

Using Media Query for Conditional CSS.

Approach 2: Using the “media” attribute in “style” or “link” Elements: 

Use the “media” attribute of the “link” element to specify that a stylesheet should only be applied when certain media types or media features are supported. You can set the “media” attribute of the “link” element to a media query.

A media query is a CSS3 feature that allows you to specify conditions for when a stylesheet should be applied. The “media” attribute of the “link” element takes a media query as its value. When the conditions of the media query are met, the styles in the stylesheet will be applied to the page. When the conditions are not met, the styles will not be applied.

Syntax:

<style media="screen and (max-width: 800px)"></style>

Example:

HTML
<!DOCTYPE html> <html>  <head>     <title>Load CSS conditionally</title>     <style media="screen and (max-width: 800px)">         body {             background-color: black;             color: white;         }          h2 {             color: green;         }     </style> </head>  <body>     <h2>Welcome To GFG</h2>     <p>Now, we are going to learn some stuff regarding CSS.</p> </body>  </html> 

Output:

Using the “Media” Attribute to load CSS conditionally

You can use a variety of media types and media features in your media queries to specify the conditions under which a stylesheet should be applied. For example, you can use the print media type to apply styles only when the page is printed, or you can use the orientation media feature to apply styles only when the screen is in landscape orientation.

Approach 3: Loading Printer-specific CSS:

When it comes to web development, it is important to have the ability to adjust styles based on the output device being used to view the website. This is where media queries in CSS come into play. By using media queries, you have the power to customize styles specifically for printing, by targeting the print output device characteristic.

With media queries, you can apply styles to your website that are specific to the printing, ensuring that the content is presented in the best possible way when printed. This is a powerful tool in your web development arsenal that can help you create a more streamlined and optimized user experience, both on screen and in print.

@media print {
/* styles specific to printing go here */
}

Media queries ensure that the styles within them are only applied during printing. To prevent unwanted styles from the screen version from carrying over, it's recommended to reset them in your main CSS.

Example:

HTML
<!DOCTYPE html> <html>  <head>     <title>Load CSS conditionally</title>     <style>         @media print {             body {                 color: black;             }              h2 {                 color: green;             }         }     </style> </head>  <body>     <h2>Welcome To GFG</h2>     <p>Now, we are going to learn some            stuff regarding CSS.</p> </body>  </html> 

Output:

Using “Media Print” to load CSS conditionally 

Explanation: In this example, the main CSS sets the font size and color for the body, while the printer-specific CSS resets these styles for the printed version of the page.

Approach 4: Loading CSS based on Dark/Light Mode:

One way to dynamically switch between dark and light mode styles in CSS is by using CSS Variables and JavaScript. The approach involves setting default values for your styles using CSS Variables, then using JavaScript to toggle between different sets of styles based on user preference or device settings.

Example: Here's a basic example of how this can be implemented:

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8" />     <meta http-equiv="X-UA-Compatible" content="IE=edge" />     <meta name="viewport"            content="width=device-width, initial-scale=1.0" />     <title>Conditional Styling</title>     <style>         :root {             --bg-color: #fff;             --text-color: #000;         }          .container {             background-color: var(--bg-color);             color: var(--text-color);             padding: 20px;         }          [data-mode="dark"] {             --bg-color: #000;             --text-color: #fff;         }     </style> </head>  <body>     <div class="container">         <!-- Your content goes here -->         <p>Welcome to GFG</p>     </div>     <button id="toggle-mode">Toggle Mode</button>     <script>         const toggleBtn = document.getElementById("toggle-mode");         const container = document.querySelector(".container");          toggleBtn.addEventListener("click", () => {             container.dataset.mode =                 container.dataset.mode === "dark" ? "light" : "dark";         });     </script> </body>  </html> 

Output:

Explanation: In this example, the CSS sets default values for the background and text colors using CSS Variables. The JavaScript then listens for a click event on the toggle button and switches the data-mode attribute on the container between dark and light. The CSS then uses the [data-mode="dark”] selector to adjust the values of the CSS Variables based on the data-mode attribute.

By using this approach, you can create two sets of styles, one for dark mode and one for light mode, and switch between them dynamically, providing a better and more personalized user experience.”


Next Article
How to skip a test in Cypress conditionally ?

V

vikash147
Improve
Article Tags :
  • Technical Scripter
  • Web Technologies
  • CSS
  • Technical Scripter 2022
  • CSS-Questions

Similar Reads

  • How to skip a test in Cypress conditionally ?
    In Cypress, there might be scenarios where you want to skip a test conditionally based on certain criteria, such as browser type, environment variables, or application state. Cypress provides several ways to conditionally skip tests, including using this.skip(), environment variables, or checking sp
    3 min read
  • CSS Conditional Rules
    CSS Conditional Rules apply CSS styles only when certain conditions are met. So the condition here can be either true or false and based on the statements/style will get executed. These rules start with the @ symbol and are part of CSS at-rules. The main conditional rules include: @supports@media@do
    4 min read
  • How to conditionally apply CSS styles in AngularJS ?
    In AngularJS we can build the dynamic single-page application with interactive CSS embedded in it. But as usual, while developing the application, the CSS is once statically defined and used, we are not changing the CSS when the application is running. But, in AngularJS we can dynamically change the
    5 min read
  • How to apply class conditionally in CSS ?
    In web development, the styling of elements on a page is a crucial aspect of creating a visually appealing and interactive website. The traditional method of styling elements involves applying the same styles to all elements of the same type. However, this approach can become limiting when creating
    4 min read
  • How to make CSS Loader ?
    The CSS loader is useful when a certain page took a few seconds to load the content of the webpage. When the user has to wait for the content to fully loaded on the webpage. If the certain webpage doesn't have the loader of CSS then the loading time the user will think that the webpage is not respon
    2 min read
  • How to use @container Property in CSS ?
    The @container CSS at-rule is a conditional group rule that styles a container context. A condition filters style declarations, which are applied to the container if the condition is true. The condition is evaluated whenever the container size or <style-feature> value changes. Table of Content
    2 min read
  • How to implement Conditional Rendering in React?
    This article explores JavaScript's conditional rendering in React JS, including various methods, syntax, and applications, leveraging React's virtual DOM, reusable components, props, and rapid rendering capabilities in single-page UI applications. We will use the following approaches to implement co
    4 min read
  • if/else condition in CSS
    In CSS, traditional if/else conditions aren't directly available. Instead, conditional styling is managed through techniques like media queries, which apply styles based on screen size, and feature queries (@supports), which check for browser support of specific CSS features, allowing adaptable and
    3 min read
  • How to add a style on a condition in Tailwind CSS ?
    In this article, we will see how to integrate conditional styling into our web projects using Tailwind CSS. There are various Tailwind CSS classes are available, although, it usually involves dynamically adding or removing classes using JavaScript. There are different approaches to implementing the
    3 min read
  • How to Create Animation Loading Bar using CSS ?
    Loading Bar with animation can be created using HTML and CSS. We will create a Loader that is the part of an operating system that is responsible for loading programs and libraries. The progress bar is a graphical control element used to visualize the progression of an extended computer operation, s
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences