1

I'm using a wordpress theme and I do want to change the css of 2 blocks using php when the value of certain variable is even or odd..

this is my code :

<?php 
            $i = 0;
            while ( have_posts() ) {

                // Override
                if(($i % 2) == 1) { ?>

                    <style type="text/css">
                        .grid-box-img {
                            width: 54%;
                            float: left;
                        }

                        .entry-head {
                            width: 56%;
                            background-color: #fff;
                            position: absolute;
                            z-index: 10;
                            margin-left: 43%;
                            margin-top: 27%;
                        }
                    </style>
                    <?php 
                }
                else { ?>
                    <style type="text/css">
                        .grid-box-img {
                            width: 54%;
                            float: right;
                        }

                        .entry-head {
                            width: 56%;
                            background-color: #fff;
                            position: absolute;
                            z-index: 10;
                            margin-top: 27%;
                        }
                    </style>
                    <?php
                } 
                $i++;
                the_post(); 
            } ?>

But, unfortunately it doesn't work... It applies only the CSS of the last value.

How can I do that ? Thank you :)

2 Answers 2

2

Best practice is that make two classes one for even and other for odd and place a if condition where it needed.

<a href="/" class="<?php if(($i % 2) == 1){ echo 'even';} else { echo 'odd';} ?> ">Link </a>

In your CSS:

.even{
//your styling for even class
}
.odd{
    //your styling for odd class
    }
Sign up to request clarification or add additional context in comments.

Comments

0

CSS applies to the whole document (HTML 5 introduces scoped stylesheets, but browser support is weak and they are a terrible solution for this problem).

If you want to indicate that different elements are different then make them members of different classes, don't try to apply different stylesheets to them.

2 Comments

Thank you. So I oly have to add the value of the variable in the class.. for example : grid-box-img-12 and then doing the test using the value 12 of the class. Right ?
You only have two different styles you want to apply, having a "12" seems silly. class="grid-box-img even" would seem to make more sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.