Modular CSS with PHP
What is Modular CSS?
- Modular CSS means splitting your styles into individual, reusable modules.
- Each module serves a specific purpose and can be used independently.
- You can easily adjust which CSS modules are included based on your needs.
How is the system structured?
CSS File Structure
CSS file structure:
config.css.php - Contains all variables and configuration settings
base.css.php - Basic styles for HTML elements
main.css.php - Collects all styles and generates the final CSS
components/* - Reusable UI components
layout/* - Layout-specific styles
pages/* - Page-specific styles
config.css.php - Contains all variables and configuration settings
base.css.php - Basic styles for HTML elements
main.css.php - Collects all styles and generates the final CSS
components/* - Reusable UI components
layout/* - Layout-specific styles
pages/* - Page-specific styles
Combining all modules in main CSS
$cssModules = [
['base', 'comment', 'Basic styles for the page'],
['base', 'styles', renderBodyStyle()],
['h2', 'comment', 'Heading level 2 styles'],
['h2', 'styles', renderH2Style()]
];
['base', 'comment', 'Basic styles for the page'],
['base', 'styles', renderBodyStyle()],
['h2', 'comment', 'Heading level 2 styles'],
['h2', 'styles', renderH2Style()]
];
How does the CSS look in code?
- You can split your CSS into as many files as you need and structure it clearly.
- Each CSS section is defined in a function, making it easy to assemble the final CSS.
function renderH2Style() {
return [
'h2' => [
'margin-top' => '30px'
]
];
}
return [
'h2' => [
'margin-top' => '30px'
]
];
}
What else is important?
Advantages of modules
- The CSS truly updates in the browser without needing to clear the cache.
- Reusability: A module can be used in multiple projects.
- Clarity: Comments and structure make the code easier to understand.
- Maintainability: Changes can be made in a targeted way.
Tips for usage
- Choose meaningful module names.
- Describe each module with a comment.
- Use helper functions for recurring styles.
💡 Didactic Note
This demo showcases a modular CSS architecture, where styles are split into reusable components. In professional projects, these modules can be shared via Composer packages or private repositories.
The implementation uses PHP to dynamically generate CSS - an advanced concept for build processes.