Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to alternate row colors in PHP/HTML?

Tags:

html

css

php

colors

Here's a PHP example of mine. Can anyone find a shorter/easier way to do this?

<? foreach($posts as $post){?>     <div class="<?=($c++%2==1)?‘odd’:NULL?>">         <?=$post?>     </div> <? }?>  <style>     .odd{background-color:red;} </style> 

Examples in other languages would be fun to see as well.

like image 741
thrashr888 Avatar asked Dec 29 '08 23:12

thrashr888


People also ask

How do you alternate colors in a table?

Select the range of cells that you want to format. Click Home > Format as Table. Pick a table style that has alternate row shading. To change the shading from rows to columns, select the table, click Design, and then uncheck the Banded Rows box and check the Banded Columns box.

What is alternate back color access?

The AlternateBackColor property contains a numeric expression that corresponds to the color used to display on alternate rows of the specified section. Use the Color Builder to set this property by choosing the Build button to the right of the property box in the property sheet.


2 Answers

Fundamentally - no. That's about as easy as it gets. You might rewrite it a bit shorter/cleaner, but the idea will be the same. This is how I would write it:

$c = true; // Let's not forget to initialize our variables, shall we? foreach($posts as $post)     echo '<div'.(($c = !$c)?' class="odd"':'').">$post</div>"; 
like image 173
Vilx- Avatar answered Oct 16 '22 15:10

Vilx-


If you'd like to have less in-line PHP, a great way of doing it is via JavaScript.

Using jQuery, it's simply:

<script type="text/javascript"> $('div:odd').css('background-color', 'red'); </script> 
like image 42
Max Avatar answered Oct 16 '22 17:10

Max