Reputation: 2707
Can we embed php code in a css file. I need to add conditions to css properties.
styles.css
<?php
if($suserid == 2)
{ ?>
.proverb { border:0px solid blue; margin-left:34px; width:250px !important; margin-top:6px; } <?php
}
else
{ ?>
.proverb { border:0px solid blue; margin-left:0px; } <?php
}
?>
Upvotes: 1
Views: 140
Reputation: 351
A file is considered PHP by the handlers your webserver attaches to a file type or file extension. If a file is considered PHP, the contents will be executed as PHP code.
Assuming you're using apache, you can add the php handler to CSS files by adding the following in your VirtualHost file or in your .htaccess file:
<Directory "/path/to/your/css/dir">
AddType application/x-httpd-php .css
</Directory>
The only downside is this changes the output mime-type to text/html of all css files in the given directory. Therefore you have to override the mime-type so browsers know you're sending css in stead of html. Trough PHP you can use: <?php header('Content-type: text/css'); ?>
on the first line of every css file.
Keep in mind changing the handler to php for css files does put more stress on your server, since every file has to be parsed before it can be sent to the output buffer. Therefore it's easier and better to just add an extra class to your html output and adjust your css accordingly, like @Rizier123 suggests.
Upvotes: 3
Reputation: 2960
Your request is bad practice. Do not proceed.
While it is technically possible to do this, you should look into alternatives. Do not dynamically generate CSS files. They will be cached by your browsers, and dynamic changes will not be propagated.
Instead, make special-case classes that you can add to the HTML. Your CSS would become:
.proverb {
border: 0px solid blue;
margin-left: 0px;
}
.proverb.user-2 {
margin-left: 34px;
width: 250px !important;
margin-top: 6px;
}
In your HTML-generating code you can have:
<div class="proverb <?php if($suserid == 2) echo "user-2"; ?>"></div>
This will add the user-2
class if the user id is 2, and gives the same result as what you wanted in your example.
Upvotes: 7
Reputation: 11597
It's possible.
First you have to tell your web server to serve *.css
files through the PHP ISAPI module, then you can embed the code.
But this is not a good practice and I'd advise not to do so. There are better solutions, like SASS and LESS.
Upvotes: 2