Media804
Media804

Reputation: 41

Inline dynamic CSS possible via PHP?

I'm looking to dynamically generate some inline CSS and was wondering if it was possible via PHP.

Basically, I'm passing multiple variables via query string and am doing some arithmetic with the values to create values for CSS. Here's what my page looks like:

<?php
$var1 = "var1";
$var2 = "var2";
$divided_amount = $var1/$var1;
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>Derp</title>
</head>
        <div style="height: <?php echo $divided_amount ?>px;">
Dynamic height content here
        </div>

</body>
</html>

This is not working out for me and I'm really trying to avoid going with an external stylesheet if possible.

Any help/insight is very much appreciated!

Upvotes: 1

Views: 1561

Answers (3)

Repox
Repox

Reputation: 15476

You are dividing $var1 with the same variable ($var1). Assuming you actually use numbers and not strings, this will always result in 1. Which means your div element will always be 1px high.

Secondly, you should ceil() or floor() your result, just to make sure that you are not using floats to set pixel height.

And remember to validate your HTML - this would have proved that something was wrong.

Here's a working example:

<?php
$var1 = "111";
$var2 = "7";
$divided_amount = floor($var1/$var2);
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>Derp</title>
    </head>
    <body>

        <div style="height: <?php echo $divided_amount ?>px; background-color: #F2F;">
Dynamic height content here
        </div>

    </body>
</html>

Upvotes: 5

Dylan Cross
Dylan Cross

Reputation: 5986

I don't think you can have decimals in pixel width, and if you're returning a value from the division with a decimal (which is almost likely) then you should round the number. Then I don't see any reason why it wouldn't work.

Upvotes: 0

jeroen
jeroen

Reputation: 91734

This should work without any problems.

Some things to look at:

  • You are dividing strings, not numbers.
  • Your html example does not have an opening body tag.
  • You can cast the result to int to make sure it is a valid number.

Upvotes: 0

Related Questions