CSS sprites background and selectors

Deadly 提交于 2019-12-24 00:06:36

问题


Thank you in advance for any help you can give. I am implementing sprites for the first time and am looking to streamline my code. Below is my css and html.

CSS

div[class^='Rating']
{ 
    background:url('http://10.0.50.19/images/Ratings.png') no-repeat;
    width:68px; 
    height:13px; 
    display:block;
}
.Rating0_5 { background-position: 0px 0px; }
.Rating1_0 { background-position: 0px -13px; }
.Rating1_5 { background-position: 0px -27px; }
.Rating2_0 { background-position: 0px -41px; }
.Rating2_5 { background-position: 0px -55px; }
.Rating3_0 { background-position: 0px -69px; }
.Rating3_5 { background-position: 0px -83px; }
.Rating4_0 { background-position: 0px -98px; }
.Rating4_5 { background-position: 0px -112px; }
.Rating5_0 { background-position: 0px -125px; }

HTML

<div class="Rating0_5"></div>
<div class="Rating1_0"></div>
....

The issue I am having is the background-position is always being set to 0px 0px as I believe the first style is overriding the background-position elements (according to Firebug). If I copy copy the background:url('http://10.0.50.19/images/Ratings.png') no-repeat; to each of the .RatingX_X styles it works fine but I don't want to repeat the background-image and repeat text if I don't have to. Hopefully this makes sense. Thanks again.


回答1:


  • The easiest and most cross-browser way would be to add a common class on your elements (<div class="Rating Rating0_5"></div>) and then simply change div[class^='Rating'] to .Rating.

  • Your other possible solution is to fix the selector specificity in your code. Either use simply [class^='Rating'] or write your class selectors as div.Rating0_5.




回答2:


Define your first rule as:

div[class^='Rating']
{ 
    background-image:url('http://10.0.50.19/images/Ratings.png');
    background-repeat: no-repeat;
    width:68px; 
    height:13px; 
    display:block;
}

and it should work.

On your background: you are not definin the position so it assumes it is on the default 0 0, and since your first selector is more specified as your background-position selectors it overrides.



来源:https://stackoverflow.com/questions/5992670/css-sprites-background-and-selectors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!