Adding background image to div using CSS

Orahmax picture Orahmax · Nov 19, 2013 · Viewed 362.8k times · Source

I have been trying to add background image to a div class using CSS, but I didn't have any success.

HTML code:

<header id="masthead" class="site-header" role="banner">
    <div class="header-shadow"></div>
        <hgroup></hgroup>
        <nav role="navigation" class="site-navigation main-navigation">

        </nav><!-- .site-navigation .main-navigation -->
</header><!-- #masthead .site-header -->

CSS:

.header-shadow{
    background-image: url('../images/header-shade.jpg');
}

Additional information:

This is an image with a shadow and I am using it at the top of the website, so it mustn't have a particular width.

Answer

Nitesh picture Nitesh · Nov 19, 2013

You need to add a width and a height of the background image for it to display properly.

For instance,

.header-shadow{
    background-image: url('../images/header-shade.jpg');
    width: XXpx;
    height: XXpx;
}

As you mentioned that you are using it as a shadow, you can remove the width and add a background-repeat (either vertically or horizontally if required).

For instance,

.header-shadow{
    background-image: url('../images/header-shade.jpg');
    background-repeat: repeat-y; /* for vertical repeat */
    background-repeat: repeat-x; /* for horizontal repeat */
    height: XXpx;
}

PS: XX is a dummy value. You need to replace it with your actual values of your image.