简体   繁体   中英

Conditional alignment of text inside html paragraph

Here is table data that sometimes needs to be aligned right, and other times needs to be aligned center:

<td colspan="5"><p align="right"><?php echo number_format($total_adjusted_taxes,2) ?></p></td>

What determines whether to align right or centered is this variable:

<?php $r_or_c = (count($categories)==1?"right":"left");    
?>

What is the best way to use this variable $r_or_c inside the p tag?

I'll write something like this. You're going to echo in place the correct value:

<p align="<?php echo count($categories)=='1' ? 'right' : 'left'; ?>">....</p>

I prefer using CSS to style elements, though, so you can use the same method to assign a different class, or just style="text-align:<?php echo....;?>"> . Using class is better because you won't need to make changes in every single paragraph you write your inline style.

If you define your variable somewhere else, and just want to echo it (like your doing, it seems):

$r_or_c = count($categories)=='1' ? "right" : "left";

<p align="<?php echo $r_or_c;?>">....</p>

As someone else said, it's better not to use this inline styling, or you'll make your code more difficult to maintain in the future. You could style the <td> instead of your paragraph also:

css:

  .left { text-align:left;}
  .right { text-align:right;}
 /* OR : */
 td.left {}
 td.right{}

html:

<td class="<?php echo $r_or_c;?>">......</td>

Also, you said "center" but wrote "left", don't know what you really need, so in case just subsitute 'left' with 'center', obviusly.

<td colspan="5"><p align="<?php echo (count($categories)==1?"right":"left");?>"><?php echo number_format($total_adjusted_taxes,2) ?></p></td>

Is that what you asked?

Just shove it in there.Not much complication to it.

<td colspan="5"><p align="<?=$r_or_c?>"><?php echo number_format($total_adjusted_taxes,2) ?></p></td>

On a side note, you should start using CSS for styling:)

.align-right { text-align: right; }
.align-left { text-align: left; }

-

<td colspan="5"><p class="align-<?=$r_or_c?>"><?php echo number_format($total_adjusted_taxes,2) ?></p></td>

As my comment to the question, as responded to by the OP:

...was indeed [what] [he] was looking for. Worked perfect[ly].

I've opted to post that comment as an answer:

I'd suggest removing the p tag entirely, and using <td style="text-align: <?php echo $r_or_c; ?>;"> . That, or assign a class-name to the td ('right' or 'center'), and use that to style the text-alignment .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM