0

I have a simple css issue but I couldn't figure it out at this moment.

I have

html

<div class='test'>
    <img src='loading' class='load'/>
    <img src='title.jpg'/>
    <img src='title.jpg'/>
    <img src='title.jpg'/>

</div>

MY css

.test img{
   margin:15px;
}

.load{
   margin:0;
}

I want the loading image has no margin at all but it seems the 15px applies to my loading image. I thought class has the hightest css level.

How do I solve this? Thanks so much!

FlyingCat
  • 14,036
  • 36
  • 119
  • 198

3 Answers3

4

Add prefix .test

.test .load {
  margin: 0;
}

score of css selector .test img is (0,0,1,1), and .load is (0,0,1,0) which is less then (0,0,1,1). By add prefix .test. The score become (0,0,2,0).

ref: http://css-tricks.com/specifics-on-css-specificity/

Tim Green
  • 3,571
  • 2
  • 23
  • 23
3

Both declarations contain one class selector. Since the first declaration also has an element selector, it is more specific and thus it takes precedence. See CSS Specificity specification for details on how that is counted (briefly: ID selectors are more specific than class selectors, which are more specific than type selectors, and having more selectors is more specific than having fewer selectors).

In your case, you can use an ID selector, since those have precedence over class selectors:

<img src='loading' id='load_img' />

#load_img { margin: 0; }

If you want to avoid IDs, you can also do as @TimGreen's answer suggests, and use an additional class selector to increase the declaration's specificity.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • I think it's better to use the class `test` in the selector [like Tim suggested](http://stackoverflow.com/a/13079428/1591669). The class is already there, while the ID would need to be added. It's also advisable to omit the use of IDs for styling as long as it is feasible. – unor Oct 26 '12 at 02:59
  • I was surprised that the first three answers didn't propose the "best" (arguably, of course) way and feared that one of these might accepted (because Tims answer had lower votes). I guess that my first comment is sufficient. Or maybe you'd like to reference the class selector way in your answer, too (can't remove vote until it's edited) – unor Oct 26 '12 at 03:09
  • Thanks for your comments. I have amended my answer. – nneonneo Oct 26 '12 at 03:33
0

Either do this: <img src='loading' style="margin: 0"/> or:

    .test img{
         margin:15px;
     }

    .test img:first-child{
         margin:0px;
     }
Math is Hard
  • 896
  • 1
  • 12
  • 24
  • The use of the pseudo-class `:first-child` would only work in this very example, as long as the "special" `img` is, well, the first one in the `div`. I think it's much neater to use `.test .load`, like [Tim suggested](http://stackoverflow.com/a/13079428/1591669). – unor Oct 26 '12 at 03:01