Quick Tip: Remove right margin from column post layout with php
One of the most popular layout styles right now is the Three Column grid, particularly for News-like websites.
Well, one of the main problems coders will run into when creating the layout with CSS is how to make all the columns fit correctly, while retaining the correct margins.
What often happens is the first two columns look great, but then the third margin will screw up because the right-margin, for example, has pushed the column outside of the containing div. The problem looks something like this:

A friend / php developer showed me a sweet solution to this problem the other day, so I thought I’d post it here for all of you.
It works by adding a counter at the beginning of your column layout that starts at “0″, then with each column, a count of “1″ is added to the initial “0″. Then, when the count reaches “3″ (or however many columns your layout has), you add an additional CSS class that removes the right margin. And finally, you reset the counter so that the next row of columns begin at “0″.
It looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<div class="row"> <?php $i=0; //start the count at "0" if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> $i++; //add 1 to the total count ?> <div class="column <?php if($i===3){ echo 'column-right'; } ?>"> <?php the_content(); //your post content ?> </div> <?php if($i===3){ echo '<div style="clear:both; width: 100%;"></div>'; $i=0; } //reset the ount to "0" and clear the divs ?> <?php endwhile; endif; ?> </div> |
The CSS looks like this:
1 2 3 4 5 6 7 8 9 10 |
.row { width: 100%; } .column { width: 33%; margin-right: 20px; } .column-right { margin-right: 0!important; } |
Enjoy!










3 Comments
PHP should be used as a last-resort in this case. Many designers won’t have PHP at their disposal to correct these types of issues.
If you want to do a 3-column (or any column layout) you should check out the CSS grid frameworks. I use Blueprint CSS when doing my grid layouts, which would look like this (hoping the comment doesn’t strip my formatting):
Column 1
Column 2
Column 3
The CSS class “last” strips the right-margin from the column.
Check out Blueprint CSS: http://www.blueprintcss.org/
You’re completely right, for some cases..
If you are able to code a rigid grid system, off course, you should probably never use PHP for this. However, when coding a wordpress theme, you do not have that luxury.
Depending on your layout, and on whether you wish to support all browsers, it would be possible to do the same thing with the :nth child psuedo class.
I’m quite familiar with Blueprint CSS, it’s a great resource.
This is an awesome trick man. I will be using this forever. Definitely in my next free theme.