user2635961
user2635961

Reputation: 379

Applying a Variable to a DIV CLASS In PHP

I am attempting to make the TOP and LEFT parameters of this DIV class variable. Here are snippets of my code

First in the style.php file:-

<?php
header("Content-type:text/css");
$top='100';
$left='200';
?>
.testbox {
     float:left;
     position:absolute;
     top:<?php echo $top; ?>px;
     left:<?php echo $left; ?>px;
     background-size:2000px 2000px;
     background-repeat:no-repeat;
     background-color:#FFFFFF;
     width:50px;
     height:100px;
     border:1px solid #b3bdc2;
     z-index:1;

     }

In my main script (gettrains.php)

        $top='100';
        $left='500';
        echo "<div style='top:$top;left:$left' class='testbox'>
        <p>$answer</p>
        </div>";

I have also put the below line into my gettrains.php script

<link href="style.php" type="text/css" rel="stylesheet" />

I basically have two problems:

1) The box is positioned at 100,200 as per style.php and NOT 100,500 .........my new variables

2) Since including the "link href="style.php.............etc at the top of the gettrains.php file it keeps reloading when previously it did not (Its part of an AJAX call (GET) that worked fine before including the LINK to style.php

Any help appreciated. Thanks

Upvotes: 0

Views: 309

Answers (1)

This is an odd thing to do, as PHP can only generate the initial HTML source that the browser receives. You're basically saying "I need the box at 100/200 and 100/500". In a battle between CSS rules, the most specific rule wins. Normally that'd be style="..." but in this case you didn't add the px unit to the inline style so the browser rejects it as meaningless.

The "quick fix" here is to simply fix that problem: echo "<div style='top:${top}px;left:${left}px' class='testbox'> but the real problem here is that you're specifying two positions mutually exclusive positions at the same time without a clear indication of why you're doing the override. Which position does it need? PHP runs server-side so it can't really have any idea why 100/500 is better than 100/200 (what are those numbers based on? Unlike on-page JavaScript, PHP can't check what is good positioning, so these are just magic numbers).

As simple positioning information for a specific element, it's much better to generate those positions as their own, named, CSS class such as:

.initial {
  top:  <?php echo $top_override; ?>px;
  left: <?php echo $left_override; ?>px;
}

and then in the HTML that you generate, use <div class="initial">... so that the master CSS applies, but the .initial class wins, setting the correct left value (since the top values are the same). Then, once the page is rendered by the browser, you'll have to use JavaScript to do any further dynamic positional changes.

Upvotes: 1

Related Questions