Well, everyone knows we can use HTML inside a PHP file. So can we also use CSS inside a PHP file and still call it like <link rel="stylesheet" type="text/css" href="mystyle.php" />
to pass PHP as a CSS file? I know we can generate CSS from PHP doing something like echo "<style>
(…) </style>"
, but will the above work?
You can do this. In the mystyle.php
, add in the first line:
header('Content-type: text/css');
Then do your code just like any PHP, using variables and such. Because of the header declaration, your php when opened by the browser will be parsed as a css file.
So you could do something like:
<?php
header('Content-type: text/css');
/* ------------------------
PHP Vars
------------------------ */
$color1 = "#fff";
$fontSize = "15px";
?>
.someSelector {
color: <?=$color1;?>;
font-size: <?=$fontSize;?>;
}
CSS is used to style markup. PHP is not markup, so you cannot apply styles.
However, if you are simply trying to use a PHP script to output CSS, you can do it the same way you would output HTML:
<?php
header("Content-type: text/css");
echo "h1 { text-decoration: underline; }";
?>
or
<?php
header("Content-type: text/css");
?>
h1 { text-decoration: underline; }
If you are attempting to output CSS from a script that also generates HTML, you can echo a <style
block like you indicated in your question, or you can use inline styles in the HTML that you generate:
<?php
echo '<h1 style="text-decoration: underline">...';
Anything outside <?php ... ?>
, or echoed by the script, will simply be passed through to the browser. It can be anything, as long as the browser understands it. In your example, the browser will interpret the output of the PHP script as CSS, so it will work.
I think it is possible if you make sure your php files returns css with the including header types.
header("Content-type: text/css");
It should work if you set
header("Content-Type: text/css");
as first line in your mystyle.php
You can do this, i.e., auto-generating CSS with PHP in the mystyle.php
script. The only thing to make it work reliably across browsers is to tell them, that it is indeed CSS:
<?php
header('Content-Type: text/css');
?>
/* your CSS here... */
I don't know what your intentions are, but if all you want is using variables I think a better approach can be using CSS preprocessor. Less is easy to learn and this solution can be quicker than executing the PHP each time a CSS is needed.