You can add dynamic PHP variables to CSS in various ways which I’ll outline here in this article. I have mentioned how to do this in raw PHP and WordPress which should cover most scenarios you will be in.
Table of Contents:
- Using PHP in CSS examples
- Can you pass a value from PHP to CSS?
- CSS and PHP in WordPress
- Javascript and PHP in WordPress
Using PHP in CSS examples:
You can use CSS with PHP together. The purpose of CSS with PHP is to style the HTML which is output to the page by PHP. While PHP does need CSS to work almost all websites use CSS to style the HTML which is added to the page via PHP. HTML is the script that the user sees on their screen when they browse your site and is produced by the PHP you write. So, how do you write CSS in PHP? Let’s go through some examples.
Example 1: How to include CSS in PHP
If you want to include an entire CSS file via PHP you can do so using the PHP code below. remember to create your own ‘style.css’ file and add the CSS to it that you would like.
<?php // if this is already on your PHP page then you don't need to include it
echo '<link rel='stylesheet' href='https://yoursite.com/folderpath/style.css' media='all' />';
The result of this on the page will be that the CSS you wrote in style.css will be included on the page. Often it’s best to add this kind of code in the <head> tag of your website although it will work any place you put this. The file with which you enter this code needs to have the .php extension and not .html or anything else.
Example 2: Writing inline CSS in PHP
In a PHP file (one with an extension of .php) you can also echo out CSS ‘inline’ in the flow of the page so to speak. You could do this in two different ways.
Example 2.1: Inline CSS using the <style> tag in PHP:
<?php // if this is already on your PHP page then you don't need to include it
echo '<style>
.myClass{font-size:3em; display: block;}
</style>';
Inside of the <style> tags you can write whatever CSS that you like. You could include this in any PHP page but often times it might come in via the <head> tag.
Example 2.2: Inline CSS using the style attribute of a <div> (or any other) tag in PHP:
It’s also possible to write inline css as an attribute of a div. This can be very useful if you are dynamically change some CSS based on a PHP variable being present or not or do some if/else logic in PHP to output CSS based on a PHP variable.
PROTIP: This is a fairly messy way to do it but it works. Best practice would say that you don’t do this because then your application has CSS written both inline and most likely in the various CSS files around your site. Used sparingly if YOU HAVE TO is acceptable.
<div class="<?php echo 'className'; ?>">Div content here</div>
OR
<div class="<?php echo $variable; ?>">Div content here</div>
In the above examples you don’t need to write this in a file with .php extension but you could actually use this in a .html file. The <?php ?> tags you see around the echo mean that the .html file will stop producing html and produce PHP within those two opening and closing PHP tags. PHP and HTML is made to work well like this deliberately.
Example 3: How to style PHP which has been echo’d with CSS
PHP echo’s HTML to the page and can be style either by writing inline CSS as per the above methods. Or indeed you can simply add a class name to the PHP which is echo’d out and use CSS from a separate CSS file or inline script tag to add CSS to it. Let’s look at an example that we haven’t already seen before.
<?php
echo '<div class="myClassName">Div Content here</div>';
Then in your style.css file you could write css for this class a la…
.myClassName{font-size: 3em;color: #fff;}
Can you pass a value from PHP to CSS?
Yes you can pass a PHP variable or value from PHP to CSS. You could do this a few different ways depending on which scenario you are in. For example, in
- example 2.2 above where you are in a .html file and want to print out a PHP variable into CSS. The PHP variable could be defined on the page someplace or perhaps is a GLOBAL or is a known PHP variable on the page.
- or you could do a variation of this as described below which is an example we haven’t seen yet. In this example the below code would be added to a file called style.php and then included in the <head> tag of your document.
<?php
header("Content-type: text/css; charset: UTF-8");
$variable = 'className';
$fontColour = '#fff';
?> // important that you close the tag here
.className{
color: <?php echo $fontColour; ?>;
}
You could then add this to the page by adding a .php file via a <link> tag in the <head? tag of the document. Note the style.php file uses .php not .css as might be expected.
<link rel='stylesheet' type='text/css' href='folderPath/style.php' />
CSS and PHP in WordPress:
PROTIP: You can learn about customizing WordPress fully in our larger guide which covers beginner, intermediate to advanced WordPress topics.
Normally you don’t need to write PHP and CSS together. This is because it is best practice in web development to ‘separate concerns’ and write CSS and PHP in separate files. In saying that every now and then you will need to add some sort of dynamic variable to your CSS for some animation or some other reason.
Adding CSS to an existing file using WordPress Native Functions:
WordPress has a native function, called wp_add_inline_style, in order to do this from your PHP or functions.php which is quite useful.
PROTIP: It will only work if there is an existing CSS file that is being loaded that you want to add to. I think this is fine because you can always add it to the default style.css because it is always loaded in a WordPress theme.
Find your functions.php file at something like, https://yoursite.com/wp-content/themes/yourtheme/functions.php and add the below code.
<?php
// existing code in functions.php
function tutorialStyles() {
wp_enqueue_style(
'tutorial-style',
get_template_directory_uri() . '/style.css'
);
$color = 'purple'
$tutorial_css = "
.myClass{
background: {$color};
}";
wp_add_inline_style( 'tutorial-style', $tutorial_css );
}
add_action( 'wp_enqueue_scripts', 'tutorialStyles' );
To explain what is going on here,
- We create a function, called tutorialStyles(), which hooks into the WordPress Native Hook wp_enqueue_scripts()
- Inside this function we utilise another WordPress function called wp_enqueue_style which gets out WordPress themes main stylesheet.
- NOTE: We enqueue the style because if we don’t the following code will not work. We need to add CSS to an existing file known to WordPress.
- Next we utilise yet another of WordPress’s Native Functions being wp_add_inline_style() to assign some PHP variables to our CSS and add it to the existing style.css.
In this way you can, from your functions.php, add PHP variables to your CSS files in your WordPress site.
Adding PHP variables to CSS by writing CSS in a PHP file:
In your header.php file which will be at something like https://yoursite.com/wp-content/themes/yourtheme/header.php add the below in between the <head> tag amongst the other HTML you find there.
<?php
// existing code inside <head> tag inside header.php
<link rel="stylesheet" type="text/css" href="<?php echo WP_CONTENT_DIR . '/themes/yourtheme/myCSSFile.php';?>">
Now we need to add a new file called myCSSFile.php at https://yoursite.com/wp-content/themes/yourtheme/myCSSFile.php
Then you can add the below code to it and add your own CSS to it,
<?php
// Could do something more complex here, connect to your database for eg. See 'protip' below.
header('Content-type:text/css');
$margin = '10px';
$color = 'blue';
?>
.className{
margin:<?php echo $margin; ?>
}
h2 {
color:<?php echo $color; ?>
}
To explain what is going on in the code above,
- First we are doing some PHP which gets our PHP variables. PROTIP: Most of the time I would expect that you would need to do some more complex calculation than simply manually print out the string values of these but as this is a PHP file you could go ahead and do that before those variables are set with your own custom code.
- Then we close off PHP tags and just write CSS but when we want to print out our variables we simply open some PHP tags and print out our variables.
- You can now check your front end and see if the CSS has been applied. Don’t forget to refresh your browser cache.
Adding inline CSS also from a PHP file:
This is my least preferable method but it gets the job done. It’s less preferable because from a maintenance point of view it’s easier to have all the CSS in one area and all the PHP in another.
The previous methods is preferred because it maintains this split but still allows you to add your PHP variables to your CSS.
But if you want to you can simply add a <style> tag with your CSS inline as it is known. This means that when the PHP is processing on the server the CSS will be printed out to the page in a <style> tag.
Add this to your PHP,
<?php
// you could echo the CSS. Replace the selectors with whatever CSS you'd like to add.
echo '<style> .className{margin:15px}, h2 {color:red}</style>';
// or in your PHP file you could stop the PHP script with a closing tag, add the <style> tag and then then open PHP again to continue doing PHP afterward
// previous PHP
?>
<style> .className{margin:15px}, h2 {color:red}</style>
<?php
// continue writing PHP
Javascript and PHP in WordPress
Normally your Javascript and your PHP are keep separate but every now and then you might want to pass some PHP variables to your jQuery or other Javascript. Let’s look at how to do that in WordPress.
Adding PHP variables to Javascript file
Doing this is much more intuitive than adding CSS as it actually works in with the rest of the WordPress Framework and we can do this from functions.php alone.
In your functions.php copy and paste the below. You can find it at https://yoursite.com/wp-content/themes/yourtheme/functions.php
$userid = get_current_user_id();
wp_add_inline_script( 'tutorial-js', 'const tutorialInfo = ' . json_encode( array(
'tutorialUserid' => $userid,
) ), 'before' );
wp_enqueue_script( 'tutorial-js', get_template_directory_uri() . '/tutorialJS.js', array('jquery'), $theme_version, false );
To explain what is going on here,
- First we set a PHP variable in WordPress, being the UserID, which we will turn into a Javascript variable later.
- We use WordPress’s Native Function wp_add_inline_script() which will allow us to take our PHP variables and make them into Javascript Variables which are accessible in the next step, ie enqueueing our javascript file.
- Then we enqueue a javascript file after our jQuery and in it we refer to and access the newly created JS variables which represent our PHP variables.
Now, we need to create a Javascript file which we can write Javascript in and reference the newly created JS variables which we made in the steps above.
Create a file at https://yoursite.com/wp-content/themes/yourtheme/tutorialJS.js
Then add the code below which will print our $userid out to the console by accessing it inside the JS variable ‘tutorialInfo.tutorialUserid’.
console.log(tutorialInfo.tutorialUserid);