Open In App

How to load css resources conditionally ?

Improve
Improve
Like Article
Like
Save
Share
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:

Loading CSS Based on Dark/Light Mode.

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.”



Last Updated : 10 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads