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?
-
Why not just echo the link?Dre– Dre2013-04-29 16:58:19 +00:00Commented Apr 29, 2013 at 16:58
-
Why do you need to do this?vcardillo– vcardillo2013-04-29 16:59:37 +00:00Commented Apr 29, 2013 at 16:59
-
You might wanna take a look hereYan Foto– Yan Foto2013-04-29 16:59:55 +00:00Commented Apr 29, 2013 at 16:59
-
@vcardillo well i know php isn't interpreted by the browser, i know we can pass a php file and it will understand it as a html, so passing a external php as a css might also work. yes i can echo it internally and not calling it as an external file, but i just had this curiosity, and right now i dont' have time to test this :Dancm– ancm2013-04-29 17:03:41 +00:00Commented Apr 29, 2013 at 17:03
-
So the only reason you want to do this is because you are curious? You shouldn't be defining your CSS in a .php file, unless there's a reason to do so. In that case, the server needs to first invoke PHP to interpret the file before its contents can be returned to the client, and thus you are adding overhead.vcardillo– vcardillo2013-04-29 17:06:39 +00:00Commented Apr 29, 2013 at 17:06
7 Answers
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;?>;
}
3 Comments
<img src="somecaptcha.php" /> with header containing Content-type: image/png and php outputting an image for e.g.)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">...';
Comments
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.