Theme Development: Make Elements With Background Images Match Image Height

Let’s say you want a responsive WordPress theme to utilize a featured image as a full browser width page banner using parallax with content above the image. Something like this:

restaurant-image
The Restaurant Theme using this technique.

To accomplish this, you’ll need to employ the use of a background image. However, background images applied to HTML elements do not inherit the height of the source image. That presents a problem when you want the element with the background image to match the height of the uploaded image. Otherwise, the element will just collapse.

Most developers use javascript or CSS height properties with media queries as a workaround. Most these solutions seem bloated or jittery. Instead, I found a solution that works well. Hacky or not, it’s simple and effective:

PHP
<?php $thumb = ( get_the_post_thumbnail() ) ? wp_get_attachment_image_src( get_post_thumbnail_id(), 'featured-image-size' ) : false; ?>

<?php if ( has_post_thumbnail() ) { ?>

  <div class="page-banner" style="background-image: url(<?php echo esc_url($thumb[0]); ?>);">
    <h1 class="headline"><?php the_title(); ?></h1>
    <?php the_post_thumbnail( 'featured-image-size' ); ?>
  </div>

<?php } ?>

Get the source of the featured image and apply it to a variable. Then, call the image path for the inline background image style. The page title and the featured image are added within the the page-banner element.

Note: The featured image added within the element is what will give the element the same height as the image.

CSS
.page-banner {
  background-position: top center;
  background-attachment: fixed;
  background-repeat: no-repeat;
  background-size: 100% auto;
  width: 100%;
  min-height: 380px;
  position: relative;
  line-height: 0;
}

.page-banner img {
  max-width: 100%;
  margin-left: -9999px;
}

Style the background properties for the element. Then hide the featured image within the element using a large negative margin.

The result is a background image applied to an element that reflects the height of the image and scales seamlessly without the use of media queries or javascript. Now parallax can be applied to the background image and content can be vertically centered within the element.


One response to “Theme Development: Make Elements With Background Images Match Image Height”

  1. Lance Avatar

    Thanks for this guide David. By the way, if you would be working on some write ups in the future, you may want to check out some resources on our blog: 1stwebdesigner.
    Here are some of the best post where you can get an idea: http://www.1stwebdesigner.com/full-stack-designer/
    Looking forward to hear from you. =)

Leave a Reply

Your email address will not be published. Required fields are marked *