How to handle a background-size: cover image in Wordpress?

Designer new to wordpress here. I want to take the featured image on a post and make it a hero image for the post single page.

The way I would normally do this is to create a div, set width to 100%, height to whatever vh I want, and then set background to the image url in the CSS with background size set to cover.

So how I'm trying to do this in Wordpress is like this:

section class="hero" style="background: url('?php echo $hero_image['url'];? ');" xmlns="http://www.w3.org/1999/html"

But that comes out a little wonky because setting background with inline styles overrides all the CSS back to default element stuff. Any ideas on how to do this better? Preferably without any plugins, as I'm trying to learn how to do as much in code as possible. Though I do already have Advanced Custom Fields and Custom Post Type UI installed and I'm using those extensively.

Topic custom-background images css Wordpress

Category Web


So Jack's answer works, and is correct, but I also found a more elegant solution for what I already had. I made the inline style background-image instead of background:

<section class="hero" style="background-image: url('<?php echo $hero_image['url'];?> ');" xmlns="http://www.w3.org/1999/html">

You can hook into a theme's header and add your style. Add this piece of code to your theme's functions.php file:

<?php 
add_action('wp_head','my_hero_image');
function my_hero_image() {
    if( is_single() ) { ?>
        section.hero {
            background-image: <?php the_post_thumbnail_url('full'); ?>;
            background-size: cover;
        } <?php 
    }
}
?>

This will add the following style to your theme's header on a single post:

<style>
    section.hero {
        background-image: YOUR IMAGE URL;
        background-size: cover
    }
</style>

which will do the trick.


Have you tried to add the background size "cover" inline as well, like so

 <section class="hero" style="background: url('<?php echo $hero_image['url'];?> ') cover;" xmlns="http://www.w3.org/1999/html">

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.