add the_post_thumbnail as CSS Background, in wordpress theme

I am trying to set my featured image as a background image in CSS.

I need to show the same featured image in two places in the HTML and CSS.

Read More

How do you use the_post_thumbnail() in CSS?

HTML

 <div class="magnify">
    <div class="large"></div>
    <img class="small" <?php the_post_thumbnail( 'large', array
    ('class' =>'img-      responsive') ); ?> />
 </div>

CSS

.large {background: url('img/image.jpg') no-repeat;}

Related posts

Leave a Reply

1 comment

  1. As Tim Malone stated in the comments, you will need to do this with inline styles. You can do something like this:

    <?php
    $thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'large');
    list($url, $width, $height, $is_intermediate) = $thumbnail;
    ?>
    
    <div class="large" style="height:<?php echo $height; ?>px;background-image:url(<?php echo $url; ?>);background-repeat:no-repeat;"></div>
    

    Note that I am using wp_get_attachment_image_src so that I can get the image dimensions in case I need them. In this case, it is to set the height of the div to the height of the image.