I know how to insert html code in php using print <<<HERE HERE;
construction. It means I can insert a link to css file. But is it possible to insert css code itself?
There are a couple of ways you can achieve this.
Lets say you have an anchor tag <a href="..">My Href</a>
and you want to add CSS to it based on certain instances.
You can easily echo that css into the anchor element like so:
<a <?php echo 'style="float: left;"'; ?> href="..">My Href</a>
The output would be: <a style="float: left" href="...">My Href</a>
You can do this with almost any HTML element.
Now let's say you have a predefined CSS class you would like to echo into an anchor tag element.
Let's say you have this CSS class in your stylesheet:
.floatLeft {
float: left;
}
You can simply echo that class into the anchor element like so:
<a href="..." class="<?php echo 'floatLeft'; ?>">My Href</a>
Which the output of that would be:
<a href="..." class="floatLeft">My Href</a>
Yes. It is possible.
There's actually two different ways.
Method 1: Inject PHP into your actual CSS. This is done by making your file .php, using regular HTML and CSS, and then doing as such:
.someclass {
/* Some code */
<?php // Whatever you wanna inject
?>
I have performed this many times, and no one knows. It may not be the most efficent way, but it's also sometimes better than doing...
Method 2: Escape your quotes and lines.
Use:
echo("/* Your css code here */ \ (to escape the line return
/* Whenever there is a quote, make sure to do the following: \" ");
If you don't escape the quote, PHP will think you're ending the string. That's bad, because the rest of your text gets ignored.
ADDITIONAL NOTE: You don't have to use print for echoing HTML. Echo works too.
Yes, you can easily do that. You can either do it in the CSS file like 'ilarsona' said, or you can do it in the HTML file itself.
For example:
<!DOCTYPE html>
<html>
<head>
<title>The Title</title>
<style>
p {<?php *Insert dynamic styles here* ?>};
</style>
</head>
<body>
<div style=<?php *Insert styles here* ?>> </div>
</body>
</html>