Jamie Bullock Jamie Bullock - 2 months ago 6
CSS Question

HTML/CSS background-image will apply to element but not a class selector?

For the life of me i cannot get this to work, any help will be much appreciated!

I am trying to apply a background image to a div class, for some reason the image will not show up, yet when i apply the same image to the body, it works perfectly, i have created a new html/css file to test and play around with it, see the examples below.

This works

HTML

<body>
<div class="topNav">
<p>Content here</p>
</div>
</body>


CSS

body {
background-image: url("images/topNav-bg.png");
background-repeat: repeat-x;
}


This doesnt

<body>
<div class="topNav">
<p>Content here</p>
</div>
</body>


CSS

.topNav {
background-image: url("images/topNav-bg.png");
background-repeat: repeat-x;
}


The only difference in the one that doesnt work to the one that does, is the css selector points to the class and not the element, any idea why it could be that I am having this problem? I have tried adding an ID also to the div, thinking with more specifity it might work, I have also tried making the div class width and height 100% thinking if the size is set it would work, but it still does nothing, and also, it surely wouldnt work on the body element if that were the case?
My css file is linked and path to the image is all correct also, otherwise it surely wouldnt work when I apply the css rule to the body element?
This seems really basic but has been bugging me for ages now!

Thanks in advance,

Jamie

EDIT

the actual code in my working page is as follows:
HTML

<div class="topNav">
<ul>
<li><a href="#">Log in</a></li>
<li><a href="#">Create account</a></li>
<li><a href="#">Contributions</a></li>
<li><a href="#">Talk</a></li>
<li><span class="glyphicon glyphicon-user" aria-hidden="true"></span> Not logged in</li>
</ul>
</div>


CSS

.topNav {
margin: 0px 0px 0px 176px;
background-image: url('../images/topNav-bg.png') !important;
background-repeat: repeat-x;
height: 40px;
width: 90.83%;
}


I thought it may be something else interfering, thats why i made the example to try and isolate the problem, it repeated itself though after I had removed all other styling from the div.

Answer
body div .topNav {
  background-image: url("images/topNav-bg.png");
  background-repeat: repeat-x;
}

I think this might work