如果在PHP中有条件,则动态更改css
问题描述:
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 :)
答
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.
答
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
}