【问题标题】:How can I apply percentage-based positioning to background-image sprites with pure CSS?如何使用纯 CSS 将基于百分比的定位应用于背景图像精灵?
【发布时间】:2013-12-08 16:37:39
【问题描述】:

我有一个带有按钮图标的 SVG 精灵。这些图标作为背景图像添加到 HTML 链接元素中。

我想使用百分比来定位精灵,但这很混乱。使用基于像素的定位,很容易确定位置。不幸的是,使用百分比时会发生以下情况:

  • 0% 水平对齐精灵的左侧到按钮的左侧。
  • 100% 水平偏移将精灵右侧与按钮右侧对齐。

给定一个有 8 个图标的精灵,应用 50% 作为偏移量会导致按钮中显示第 4 和第 5 个图标之间的空间。

去这里的正确方法是什么?

【问题讨论】:

    标签: css button background icons sprite


    【解决方案1】:

    精灵的宽度取决于精灵中图标(图像)的数量:一个图标(通常)应该是它必须覆盖的按钮宽度的 100%。所以对于 8 个图标:

    background-position: 800%;
    

    图标 i(第一个:i=1,第二个 i=2 等)与图标总数 n 的偏移量计算如下:

    偏移量百分比 = (i - 1 / n - 1) * 100%

    因此对于精灵第一行中的第 5 个图标 8,偏移量 = (5-1/8-1)*100% = 57,142 %

    background-position: 57.142 top;
    

    SASS 混合:

    @mixin background-position($number: 1){
        $total: 8; /* The number of icons in the sprite, placed next to one another */
        background-size: percentage($total); /* Results in 800% for 8 icons */
            background-position: percentage( ($number - 1)/($total - 1) )  top; /* My sprite has the default state in the top row, :active states in the bottom */
    }
    

    使用像 SASS 这样的预处理器可以让您灵活地在稍后阶段向精灵添加图标,而无需更改所有先前计算的背景位置。

    当然,此解决方案适用于任何具有背景图像的元素,而不仅仅是按钮。

    【讨论】:

      【解决方案2】:

      我发现这个链接对于理解背景​​位置如何使用百分比非常有用。 http://blog.vjeux.com/2012/image/css-understanding-percentage-background-position.html

      我认为将它与精灵一起使用是非常棒的。但是按照建议使用 SASS/LESS 绝对可以节省大量工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-30
        • 1970-01-01
        • 2014-02-01
        相关资源
        最近更新 更多