CSS精灵中的背景位置无法正常工作

6
我无法使用CSS的"background-position"属性来定位图片的特定部分,我设置了位置,并可以加载所有图像,但指定的区域未显示。我已经尝试写了下面这段代码,但没有成功:

<head>

<style type="text/css">

ul#links {
    list-style: none;
}

ul#links li a{
    float: left;
    padding: 40px;
    background: url('http://static.tumblr.com/wgijwsy/ixYlr91ax/sprite_colored.png') no-repeat; 
}

#customlink {
    width: 24px;
    height: 24px;
    background-position: -0px -0px ;
    background-repeat: no-repeat;
}

#rss {
    width: 24px;
    height: 24px;
    background-position: -24px -0px;
    background-repeat:no-repeat;
}

#facebook {
    width: 24px;
    height: 24px;
    background-position: -0px -24px;
    background-repeat:no-repeat;
}

#flickr {
    width: 24px;
    height: 24px;
    background-position: -24px -24px;
    background-repeat:no-repeat;
}

#twitter {
    width: 24px;
    height: 24px;
    background-position: -0px -48px;
    background-repeat:no-repeat;
}

#linkedin {
    width: 24px;
    height: 24px;
    background-position: -24px -48px;
    background-repeat:no-repeat;
}

#google {
    width: 24px;
    height: 24px;
    background-position: -0px -72px;
    background-repeat:no-repeat;
}

#foursquare {
    width: 24px;
    height: 24px;
    background-position: -72px -0px;
    background-repeat:no-repeat;
}

</style>

</head>

<body>
    <ul id="links">
    <h2>Social Networks</h2>
    <li><a href="" id="customlink"></a></li>
    <li><a href="" id="rss"></a></li>
    <li><a href=""id="facebook"></a></li>
    <li><a href=""id="flickr"></a></li>
    <li><a href="" id="twitter"></a></li>
    <li><a href="" id="linkedin"></a></li>
    <li><a href=""id="google"></a></li>
    <li><a href=""id="foursquare"></li>
    </ul>

</body>
</html>
2个回答

5
由于ul#links li a比例如#facebook更具体,因此ul#links li a中的background规则正在覆盖#facebook上的background-position
background拆分为background-imagebackground-repeat是一个简单的修复方法:
ul#links li a{
    float: left;
    background-image: url('http://static.tumblr.com/wgijwsy/ixYlr91ax/sprite_colored.png');
    background-repeat: no-repeat;
    width: 24px;
    height: 24px;
}
#facebook {
    background-position: -0px -24px;
}

1

你可能会有点混淆如何给LI和实际的A元素设置样式,因为有些样式正在覆盖你设定的样式。

这里有一个可用的代码片段,希望能为你指明正确的方向 :)

http://jsfiddle.net/JAahh/1/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接