CSS background images in WordPress

106,381

Solution 1

PHP code cannot run in .css file, however you can use inline style, such as:

<div style="background-image: url("<?php //url ?>");">

or

<style>
  .class-name {
    background-image: url("<?php //url ?>");
  }
</style>

The above would be useful when working with custom fields for dynamic image paths.

If the image is located in the theme directory, PHP won't be needed, let's say the image folder is directly under the theme folder /theme-name/images, and the stylesheet is /theme-name/style.css, then you can just add the background image to the css file as follows:

.class-name {
  background-image: url("images/file.jpg")
}

Solution 2

You don't need to use PHP in this question, your CSS file is already in template folder, so you can call image just like this:

background-image: url("images/parallax_image.jpg");

So you don't need to know template path to call images from your theme.

Solution 3

If the image folder is in the theme folder you can use:

background-image: url("/wp-content/themes/themeNameHere/images/parallax_image.jpg ");

Solution 4

Just upload your image to the WordPress Media Library

After that, you can give the path of the uploaded file in your CSS like this:

background-image:url('/wp-content/uploads/2019/12/filename.png');

Note: Open the uploaded image, there will be a path

Solution 5

One way would be to add this CSS to a PHP page that has access to the bloginfo() function. Say in index.php, you would add...

<style>
  .some-element { 
    background-image: url("<?php bloginfo('template_directory'); ?>/images/parallax_image.jpg ");
  }
</style>
Share:
106,381

Related videos on Youtube

Reece
Author by

Reece

Updated on February 24, 2022

Comments

  • Reece
    Reece about 2 years

    Is it possible to get a background image in CSS like you normally do in HTML when working with WordPress. I've tried doing this but it doesn't work.

    background-image: url("<?php bloginfo('template_directory'); ?>/images/parallax_image.jpg ");
    
  • codecandies
    codecandies over 6 years
    Style attributes are not standard conform anymore and considered harmful. See stackoverflow.com/questions/2612483/…