1

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!

3
  • Are amounts strings? If ints, what's not working? It should Commented Jan 16, 2012 at 22:32
  • What is not working? The pure fact that you divide two literal strings? Commented Jan 16, 2012 at 22:33
  • Have you inspected the div with a tool such as firebug to see if the height is in fact there and it's merely not being rendered by the browser as you might expect? Commented Jan 16, 2012 at 22:33

3 Answers 3

5

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.