【问题标题】:How do I properly set my background position when working with a sprited image?使用精灵图像时如何正确设置背景位置?
【发布时间】:2018-11-30 01:51:16
【问题描述】:

我正在处理我网站的导航元素,我想在垂直列表中添加一些图像作为可点击链接,可以用作我的导航元素:

<nav>
    <ul style="display:inline">
        <li style="height: 12px; width:34px; background: url(backgroundsprite.gif) 0 0;"></li>
    </ul>
<nav>

当我将背景位置坐标设置为 0 0 时,上面的代码有效并显示了我希望它显示的内容(精灵的一部分,主图像)。但如果我将坐标设置为其他任何值,图像不会不出现。如何正确显示精灵图像的不同部分?

附上我正在使用的图像。

【问题讨论】:

    标签: css sprite


    【解决方案1】:

    您需要指定background-position,就像为带有position: relative 的元素指定lefttop

    E. G。如果您需要将元素向上移动 10 像素,请设置 top: -10px
    移动背景的方式相同:

    a {
      display: block;
      height: 16px;
      margin-top:3px;
      background-image: url(https://i.stack.imgur.com/n1GGF.gif);
    }
    
    a[href='home.html'] {
      width: 38px;
      background-position: -36px 0;
    }
    
    a[href='aboutme.html'] {
      width: 60px;
      background-position: 0 -18px;
    }
    <nav>
      <a href="home.html"></a>
      <a href="aboutme.html"></a>
    <nav>

    但我强烈建议您使用文本而不是文本的图片。它会给您带来好处:轻松更改文本本身及其字体属性,更适合 SEO 和屏幕阅读器。

    我还简化了你的代码,也许你会发现它也很有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多