use*_*810 4 html css css-sprites
我的菜单如下:
<ul>
<li><a href="#">First Item</a></li>
<li><a href="#">Long Item</a></li>
<li><a href="#">Very very short Item</a></li>
<li><a href="#">Another Item</a></li>
<li><a href="#">Last Item</a></li>
</ul>
Run Code Online (Sandbox Code Playgroud)
我想在CSS中使用精灵图像作为背景.我希望图像以不同宽度的菜单项为中心.目前,对于第一项正确的CSS是:
background: url(images/sprite.png) no-repeat -20px -10px;
Run Code Online (Sandbox Code Playgroud)
对于第二个:
background: url(images/sprite.png) no-repeat -24px -10px;
Run Code Online (Sandbox Code Playgroud)
对于第三个:
background: url(images/sprite.png) no-repeat -32px -10px;
Run Code Online (Sandbox Code Playgroud)
等等.我不知道每个元素的确切宽度,它可以随时改变.
我可以访问HTML结构,所以如果需要,我可以添加一些标签.在这种情况下,是否可以将背景图像居中?
bre*_*ine 11
基本上,您创建一个伪元素,使用position: absolute并left:50%使其居中.
li a { position: relative;} /* makes the (position:absolute) below work */
li a:after{
content: "";
position: absolute;
top: 0;
left: 50%; /* centers the left edge of the sprite */
margin-left: -8.5px; /* this centers the actual sprite--this is half the sprite-window width. if you don't do this, the left edge will be centered instead of the center of the sprite. */
width: 15px; /* set window to see sprite through */
height: 18px; /* set window to see sprite through */
background: url(https://www.google.com/images/nav_logo129.png) no-repeat -15px -327px; /* set up the sprite. Obviously change this fto make each one different. */
}
Run Code Online (Sandbox Code Playgroud)