Make width % based off generated content
I was wondering if there is a way to make a set width percentage based off the number of posts generated by wordpress.
What I"m trying to do is create a row that will sometimes have 3 or 4 items in it and I would like the to fill up 100% so when there is 4 have each div be 25% but when there are 3 divs have them be 33%.
<div class="talent"></div>
<div class="talent"></div>
<div class="talent"></div>
I would give talent a width of 33%, but sometimes it will generate 4 divs
<div class="talent"></div>
<div class="talent"></div>
<div class="talent"></div>
<div class="talent"></div>
In which case I would want them to have 25% width, is there a certain way to go about doing this?
Solutions
You could either use
display:table
http://fiddle.jshell.net/PJ7e8/1/
section {
display:table;
table-layout:fixed;/* will basicly evenly lay cells if no width provided */
width:100%;
}
section div {
display:table-cell;
border:solid;
}
section div:nth-child(odd) {
background:#cde
}
or
display:flex
; http://fiddle.jshell.net/PJ7e8/2/
section {
display:flex;
}
section div {
flex:1;/* same value for all , width will evenly be dispatch */
border:solid;
}
section div:nth-child(odd) {
background:#cde
}
HTML used :
<section>
<div class="talent">talent</div>
<div class="talent">talent</div>
<div class="talent">talent</div>
</section>
Yeah, this is totally doable. First, you need to count the number of posts generated by the query. Something like:
if(have_posts()){
$num_displayed_posts = ($wp_query->found_posts > get_query_var('posts_per_page')) ? get_query_var('posts_per_page') : $wp_query->found_posts;
$layout_class = ($num_displayed_posts > 3) ? '4-col' : '3-col';
//now you can apply this variable to your divs classes
}
- So, count the posts with Wordpress functions
-
generate a variable depending on the number of posts displayed (hence the
get_query_var()) - apply that variable to your div in the loop
Hope that helps. Let me know if you need clarification.