开发者

How to compare a variable in PHP and change CSS depending on result

How can I test if the value of a PHP variable equals a number, and then change an element's css on that n开发者_如何学运维umber.


Considering that PHP is executed on the server, generating the page, you could use something like this :

<?php if ($variable == 10) : ?>
    <p class="firstclass">plop !</p>
<?php else : ?>
    <p class="otherclass">plop !</p>
<?php endif; ?>


Or, using the condition to only change the CSS class :

<p class="<?php echo $variable == 10 ? 'firstclass' : 'otherclass'; ?>">plop !</p>


I'm assuming the CSS is in a different file. You can use PHP to dynamically generate CSS. Instead of using style.css you use style.php and include the code:

<?php
header("Content-type: text/css");
?>

At the beginning of the file. This tells the user that this file is to be treated as a style sheet. This allows you to send data to the stylesheet. For instance, you use GET to to send a color code for a specific element. You use PHP on the HTML page to make a stylesheet link to style.php?color=#FFFFFF and in the stylesheet you use this:

element {
color: <?php echo $_GET["color"];?> ;
}

If this doesn't work, let me know.


You could use is_numeric() and a switch() statement to output the CSS number if it is inline. If your CSS is not inline, you can use separate classes and change the class.

Link - http://php.net/manual/en/function.is-numeric.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜