John Smith
John Smith

Reputation: 8821

Is using the HTML style tag bad practice? How else can I accomplish this?

Currently I'm doing something like this:

<?php
if ($x == 0)
  $image = 'background-position: 0px -7px';
else
  $image = 'background-position: 0px -14px';
?>
<a class="asdf" style="<?php echo $image; ?>"></a>

Is this the recommended way to change an image based on a variable in HTML/PHP? Is there any way to refactor this?

Upvotes: 0

Views: 398

Answers (4)

Michael Moussa
Michael Moussa

Reputation: 4297

Try something like this:

<?php
    $positionClass = ($x == 0) ? 'position1' : 'position2';
?>
<style type="text/css">
    .position1 { background-position: 0px -7px; }
    .position2 { background-position: 0px -14px; }
</style>
<a class="asdf <?php echo $positionClass;?>"></a>

PHP will set which class should be used, and then echo the corresponding class in your HTML. The CSS will be applied with the desired positioning attributes.

Upvotes: 2

Gekkie
Gekkie

Reputation: 1046

You're code is weird? At the end of the if-statement the position would end up begin -7 or -14px... the first is just nonsense...

thus this code might be 'neat'-er but thats just personal:

<a class="asdf" style="background-position: 0px -<?php echo (($x==0)?'7':'14') ?>px;"></a>

Again, some might argue that this inline tenerary operator might be unreadable, but it does the same thing...

Upvotes: 1

Brad
Brad

Reputation: 163232

I would probably set a class instead, and change the class via PHP. This way, you are still maintaining style in your CSS, but can choose it with PHP.

Upvotes: 0

zzzzBov
zzzzBov

Reputation: 179046

If it's part of the style, use css and classes. If it's part of the content, you should be using an img element.

Upvotes: 1

Related Questions