【问题标题】:Combine the background image position in the element with position in the image sprites将元素中的背景图像位置与图像精灵中的位置结合起来
【发布时间】:2015-05-26 21:49:46
【问题描述】:

我有一个元素(h3),我想把背景位置设置在右边,很简单:

background: url('/images/icon-popular.png') no-repeat right center;

但我想在有很多其他图标(图像精灵)的地方使用 .png 文件,通常我会这样做:

background-image: url('/images/icons-info.png');
background-position: 0 -110px;

如何将文件中的背景位置与元素中的“右中心”位置合并?

【问题讨论】:

    标签: css css-position


    【解决方案1】:

    这里有一个和你类似的帖子:Using Css Sprites and background position

    但就个人而言,我将如何使用像h3:before 这样的伪选择器来实现此效果,将其样式设置为匹配精灵中图标的大小并将该元素定位到h3 的右侧。

    h3 {
        background-color: #faa;
        padding:5px 10px;
    }
    
    h3:before {
        float: right;
        display: block;
        content: "";
        width: 35px;
        height: 23px;
        background: transparent url('https://jsfiddle.net/img/logo.png') no-repeat left top;
    }
    

    https://jsfiddle.net/3sdj4tga/

    您的方法可能存在的问题是,如果 h3 占用的空间比您在 sprite 中分配的空间多,则图像的其他部分将显示出来,产生不良影响。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-29
      • 2013-03-31
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      相关资源
      最近更新 更多