Book a Free Call

Create varying video heights with SCSS based on the number of posts (wp_query)



I needed to calculate the height of a video tag based on how many were on screen, inside a wp_query loop. Here’s what I did:

<?php
   $args = array(
   	'post_type'=>'post',
'posts_per_page' => 3
   );
   $category_posts = new WP_Query($args);
//added a total count of the posts here, a variable called $countage...
   $countage = $category_posts->post_count;
   if($category_posts->have_posts()) :
//continue as normal here...

Then inside the loop, where there might be a video to be displayed, I added a class with the countage variable stuck to the end of it

....if a video is happening:
<?php }else{ ?>
	<div class="card-image hasvideo_<?php echo $countage; ?>" style="background-image: url(<?php echo $theimage; ?>);">
<video controls="true" playsinline autoplay muted loop preload="none" id="barvid" class="blogvid"><br> <source loop src="<?php echo $blogvid;?>#t=0.1" type="video/mp4"/></video>
	</div>
<?php }?>

the class ‘hasvideo_<?php echo $countage; ?>’ will return ‘hasvideo_1’ on a single video, ‘hasvideo_2′ if there are 2, or’ ‘hasvideo_3’ if there are three videos.

Next I added the CSS (well, SCSS actually )to control these:

  .card-image.hasvideo_1{
    @media screen and (min-width:768px) {
      height: calc(80vw / 1.777);  
    }
    @media screen and (max-width:767px) {
      height: 45vw;
    }
  }
  .card-image.hasvideo_2{
    @media screen and (min-width:768px) {
      height: calc(40vw / 1.777);  
    }
    @media screen and (max-width:767px) {
      height: 45vw;
    }
  }
  .card-image.hasvideo_3{
    @media screen and (min-width:768px) {
      height: calc(26.66666666vw / 1.777);  
    }
    @media screen and (max-width:767px) {
      height: 45vw;
    }
  }

Here, if there are two videos, it will divide 40vw by 1.777 to keep the ratio to 16:9

If there are three videos, the width would be less again.

Hope this helps someone.

Need rapid website development:

For smaller projects at high speed


  • Adding script tag embed to Gatsby component

    Read More
  • Get more than 100 queries in GraphQL (I felt stupid)

    Read More
  • Animate on Scroll (AOS) into Nuxt js

    Read More
  • WordPress Super-admin hack

    Read More
  • Add content or ACF field under thumbnail/image gallery in Woocommerce

    Read More

Tags


Categories

Is it urgent? Donate to Cork Simon

Got an urgent issue?

Charlie's Cottage, Carrigrohane, Co. Cork, T12 WY9H

(085) 7686677