Set featured image as background in div

After scouring the internet I found a way to set a WordPress featured image as a background image in a div. The problem now is that I’m only ably set the styles for the background image of that div in-line. I want to be able to set the styles in my css file, but am unsure how.

Here’s my code:

Read More
<?php
$src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 5600,1000 ), false, '' );
?>
<div style="background: url(<?php echo $src[0]; ?> ) no-repeat center; width:100%; height: 300px; background-size:cover;"></div>

Any help would be appreciated.

Related posts

Leave a Reply

2 comments

  1. CSS files are static, but WordPress’s featured images and attachments are dynamic. The best way to handle this would be set the background-image inline, and set the rest of the background properties in the CSS file.

    PHP

    <div class="featured-image" style="background-image: url('<?php echo esc_url( $src[0] ); ?>')"></div>
    

    HTML

    .featured-image {
        background: no-repeat center;
        width: 100%;
        height: 300px;
        background-size: cover;
    }