Lazy-CSS

Lazy CSS: Client-Side Just-In-Time Utility CSS

License: MIT

Lazy CSS is a lightweight, dependency-free JavaScript library that provides an on-demand, utility-first CSS styling experience directly in the browser. Inspired by utility-first frameworks like Tailwind CSS, Lazy CSS dynamically generates CSS rules only for the utility classes you actually use in your HTML, eliminating the need for a build step and resulting in minimal CSS payloads.

It combines a set of predefined base styles (lazy.css, automatically linked) for common layouts and resets with a powerful dynamic engine (lazy.js) that parses your classes and generates specific styles for colors, spacing, sizing, responsiveness, pseudo-states, and arbitrary values on the fly.

Here’s a boiler plate:-

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
     window.lazyCssConfig = {
        screens: {
            height: {
                min: { sm: '400px' },
                max: { md: '700px' }
            },
            width: {
                min: { sm: '640px', md: '768px', lg: '1024px', xl: '1280px' },
                max: { xl: '1400px' }
            }
        },
        theme: {
          aliases: {},
          extend: {
            colors: {},
            spacing: {},
            borderRadius: {},
            fontSize: {},
            height: {},
            width: {},
            transitions: {}
          }
        },
        plugins: []
      };
  </script>
    <script src="https://lkkhwhb.github.io/Lazy-CSS/lazy2.js" defer></script>
</head>
<body class="">
    
</body>
</html>

Key Features

Installation

  1. Download the lazy.js file.
  2. Include the script in your HTML file, preferably with the defer attribute in the <head> or at the end of the <body>.
  3. You may use the CDN version for quick testing purpose.
    <script src="https://lkkhwhb.github.io/Lazy-CSS/lazy.js"></script>
    

    New features are first added to lazy2.js so if you like to try new features please feel free to use

    <script src="https://lkkhwhb.github.io/Lazy-CSS/lazy2.js"></script>
    
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lazy CSS Example</title>
    <!-- 
      IMPORTANT: If using custom config, place it BEFORE the lazy-css.js script.
    -->
    <script>
      window.lazyCssConfig = {
        theme: {
          extend: {
            // Example: Add custom colors or aliases
            colors: {
              primary: 'blue-600', // Alias existing color
              brand: '#ff6600',    // Add a new custom color value
            },
            // Example: Add custom spacing values
            spacing: {
             'xl': '3rem',
             '2xl': '4rem',
            }
          }
        }
      };
    </script>

    <!-- 
      Include the Lazy CSS script. 
      It will automatically add a <link> tag in the <head> 
      for the base lazy.css stylesheet from its CDN location.
      No need to link lazy.css manually unless you host it yourself
      and modify the script's CDN link.
    -->
    <script src="path/to/your/lazy-css.js" defer></script> 
</head>
<body>
    <!-- Your HTML content using Lazy CSS classes -->
    <div class="flex items-center justify-center h-screen bg-gray-100">
      <button class="p-4 bg-primary c-white rounded-lg hover-(bg-blue-700) active-(bg-blue-800)">
        Click Me (Uses 'primary' from config)
      </button>
    </div>

    <div class="m-xl bg-brand c-white p-4">
      Uses 'xl' spacing and 'brand' color from config.
    </div>
</body>
</html>

Note:

Usage

Add utility classes directly to your HTML elements. Lazy CSS detects these classes and generates the necessary CSS rules dynamically, complementing the base styles from lazy.css.

Example:

<!-- Background color, padding, text color, dynamic rounded corners -->
<div class="bg-green-100 p-6 c-green-800 round-12"> 
  This is a styled div (12px border radius).
</div>

<!-- Flexbox layout using base classes and dynamic gap -->
<div class="flex justify-between items-center p-4 border-b-[1px,solid,gray-300] gap-4">
  <span>Left Item</span>
  <span>Right Item</span>
</div>

<!-- Responsive padding using dynamic classes -->
<div class="p-4 md-(p-8,bg-blue-50)"> 
  Padding changes and background appears on medium screens and up.
</div>

<!-- Hover and active effects using dynamic classes -->
<button class="bg-purple-500 c-white p-2 rounded hover-(bg-purple-700) active-(bg-purple-900,scale-[0.98])">
  Hover & Click Me
</button>

<!-- Arbitrary width and margin -->
<div class="w-[80%] m-[auto]">Centered content</div>

<!-- Calculated height (500 - 50 = 450px) -->
<div class="h-500-50 bg-red-100">Height is 450px</div> 

<!-- Grid layout using base and dynamic classes -->
<div class="grid gridCols-3 gap-2 p-4">
  <div class="bg-gray-200 p-2">Col 1</div>
  <div class="bg-gray-200 p-2">Col 2</div>
  <div class="bg-gray-200 p-2">Col 3</div>
</div>

Syntax Reference

Lazy CSS combines predefined static classes from lazy.css with dynamically generated classes parsed by lazy-css.js.

1. Base CSS Utilities (lazy.css)

The lazy.js script automatically links the lazy.css file, which provides common, static utility classes (these are not dynamically generated). Key categories include:

(Refer to the actual lazy.css file for the complete list and exact definitions.)

2. Dynamically Generated Classes (lazy.js)

These classes are parsed by the JavaScript and turned into CSS rules.

a. Colors:

b. Sizing, Spacing, Font Size, Radius (Numeric Values):

c. Theme Values (Requires Configuration):

d. Arbitrary Values (Bracket Notation):

e. Responsive Design:

f. Pseudo-classes:

g. Borders (Shorthand):

h. Special Multi-Value Utilities:

i. Grid Template Columns:

j. Z-Index:

Configuration (window.lazyCssConfig)

Provide a global configuration object before the lazy-css.js script loads to extend the theme.

<script>
  window.lazyCssConfig = {
    theme: {
      extend: { // Only 'extend' is currently supported
        // Define or override colors
        colors: {
          'primary': '#1a1a1a',      // Add new color 'primary'
          'secondary': 'orange-600', // Alias 'secondary' to orange-600
          'danger': 'red',           // Alias 'danger' to default red (red-500)
          // 'blue-500': '#3B82F6',  // Can technically override defaults too
        },
        // Define theme spacing values (used by m-key, p-key, gap-key)
        spacing: {
          '1': '0.25rem', '2': '0.5rem', '4': '1rem', 'px': '1px', 'auto': 'auto',
          'gutter': '1.5rem', // Custom key
        },
        // Define border radius values (used by round-key)
        borderRadius: {
          'sm': '0.125rem', 'md': '0.375rem', 'lg': '0.5rem', 'full': '9999px',
        },
        // Define font size values (used by fs-key)
        fontSize: {
          'xs': '0.75rem', 'sm': '0.875rem', 'base': '1rem', 'lg': '1.125rem',
        },
        // Define height values (used by h-key)
        height: { 'screen': '100vh', 'auto': 'auto', 'px': '1px', 'full': '100%' },
        // Define width values (used by w-key)
        width: { 'screen': '100vw', 'auto': 'auto', 'px': '1px', 'full': '100%' }
      }
    }
    // ... other config options might be added in the future
  };
</script>
<script src="path/to/lazy-css.js" defer></script>

When using theme keys (e.g., p-gutter, fs-lg, round-md), Lazy CSS looks up the value in your configuration under the appropriate category (spacing, fontSize, borderRadius). You can also use configured color names like bg-primary.

How It Works

  1. Initialization (DOMContentLoaded): Waits for HTML parsing, loads config, links lazy.css, creates a <style id="lazy-css-generated"> tag.
  2. Initial Scan: Finds all elements, collects unique classes, generates initial CSS rules for dynamic classes found, and injects them into the <style> tag.
  3. Mutation Observer: Watches the document for added/removed elements or changes to the class attribute.
  4. Handling Changes: When mutations occur, gathers new/affected class names, debounces processing with requestAnimationFrame, parses new classes, generates corresponding CSS rules (handling responsive/pseudo-classes), and efficiently inserts new rules into the stylesheet using sheet.insertRule(), utilizing caches to avoid redundant work.

Performance Considerations

Comparison to Build-Time Tools (e.g., Tailwind CSS)

Choose Lazy CSS when the simplicity of a no-build, client-side solution is paramount for your project. (lease note that this is the CDN version of LAZY CSS and not the actual software)

Contributing

Contributions are welcome! Please feel free to fork the repository, create a branch, make changes, and submit a pull request. Ensure your code is clear and follows the existing style.

License

Lazy CSS is open-source software licensed under the MIT License.