Skip to content
Advertisement

Accessing PHP variables in CSS file

I would like to dynamically set styling of items based on the scenario in the browser. I have a set of buttons set up in HTML, content populated through PHP.

On clicking a button, a modal appears with a set of buttons in it. The number of buttons populated in the modal changes depending on the button clicked. Therefore I need dynamic css, so the positioning of the buttons adapts to the number of buttons. This way I avoid scrolling and the UI looks better, which leads to an overall better User Experience.

I used the process described in following url to set up a css stylesheet with .php extension. Then I connected the stylesheet to the application and set some variables in php which, if they are changed, change the css styling.

https://css-tricks.com/css-variables-with-php/

My stylesheet is connected to the page, and the PHP variables are correctly set up to communicate with the css code in it. Now the question is: how can I access these PHP variables in the CSS stylesheet through PHP code executed on my page?

A simple example:

My CSS Stylesheet with PHP extension (stylecss.php)

<?php header("Content-type: text/css; charset: UTF-8"); 

    $vcaModal_itemWidth = 25;
    $vcaModal_itemHeight = 50;

?>

.vcaMenu_redesign_item{
    width: <?php echo $vcaModal_itemWidth . "%"; ?>;
    height: <?php echo $vcaModal_itemHeight  . "%"; ?>;
}

In my Page (simplified example):

if($num_items > 10){

    HOW DO I CHANGE $vcaModal_itemWidth TO 50, so the percentage changes dynamically?

    <button class="vcaMenu_redesign_item"></button>

}

If the number of retrieved items is larger than 10 change the width of my generated html element accordingly.. How do I access/ change a variable in my CSS stylesheet with .php extension with PHP code on my page?

Advertisement

Answer

Using your current set up, you cannot effect changes to your CSS file by modifying the variables inside of PHP “live” – that’s not how PHP works. At best, you’d need some sort of state involved to store the values, and then re-render your CSS file from the server.

To be honest, this sounds much more of a job for the client than the server. Why not investigate using Javascript to manipulate CSS, instead of PHP?

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement