PHP variables used in inline CSS
Using PHP variables in CSS has many advantages, one of which is that you do not need to learn new syntax. Using PHP variables in CSS code is a well-known practice that has already been implemented in many frameworks, themes, and other scripts related to the site.
The most common use is inline CSS . The following is an example of inline CSS using PHP variables:
<html> <head> <style> .class { color: <?php echo $text_color; ?> } </style> </head> <body> </body> </html>
This method is commonly used when the PHP variable represents a user parameter set through the admin interface. One practical example would be in the WordPress Theme, where the user can set the background or text color through a theme backend.
PHP variables in an external CSS file
When it comes to external CSS files, it is also possible to use PHP variables, but to avoid a PHP file parsing your CSS file every time it is removed, you need to save the output to a static file, such as stylesheet-processed.css .
Both SASS and LESS need to be analyzed before saving in the " .css " file. The same goes for your PHP file, which you must execute and save the output in a static .css file, as well as in other syntax.
CSS file parsing is a very common practice and is widely used on many websites and on the most famous websites. Usually it increases site performance by decreasing (~ 25% saving) CSS code, merging multiple files into one (fewer HTTP requests), and gzip (saving ~ 80%) of the resulting files.
Here is an example of how you will use PHP variables in a file called stylesheet.php and save the result in stylesheet.css :
<?php
Place the above PHP code in a file called " parse-css.php " and access it through your web browser to create or update the resulting static CSS file.
And then in your HTML code you should include stylesheet.css instead of stylesheet.php .
You can improve your parser so that it also reduces CSS code, for example, using the CSSMin PHP class.