代码之家  ›  专栏  ›  技术社区  ›  Eric

如何将背景图像放置在离其容器右侧绝对距离的位置?

css
  •  3
  • Eric  · 技术社区  · 15 年前

    我可以将一个小的背景图像/图标放置在距离其容器左中心4像素的位置,使用:

    background: url(...) no-repeat 4px 50%;
    

    如何将其定位在距离 正确的 ?

    5 回复  |  直到 12 年前
        1
  •  7
  •   ScottS    15 年前

    根据您的情况和您希望支持的浏览器,这是可行的(在IE7-8、Firefox上进行了测试):

    background: url(...) no-repeat right 50%; border-right: 4px solid transparent;
    

    编辑时添加: 如果上述方法不起作用,因为您使用的是边框,并且您不关心IE7(还不确定我们是否完全了解),并且您的“图标”宽度是已知的,那么您可以:

    .yourContainer {
      position: relative;
    }
    
    .yourContainer:after {
      content: ' '; 
      display: block; 
      position: absolute; 
      top: 0; 
      bottom: 0; 
      right: 4px; 
      width: 10px; //icon width
      z-index: -1; //makes it act sort of like a background
      background: url(...) no-repeat right 50%;
    }
    
        2
  •  2
  •   Charlie Salts    15 年前

    怎么样

    background: url(...) no-repeat right 50%;
    padding:0px;
    padding-right:4px;
    

    以防你想要一个边界

        3
  •  0
  •   Pekka    15 年前

    流行技巧:

    • 在图像中添加4倍的透明边距 background-position: right

    • 添加4px margin-right 元素(在某些情况下有效,在其他情况下不起作用)

    • 使用jQuery确定元素的权重并调整图像位置(恶心!)

        4
  •  0
  •   Eric    12 年前

    new way to specify background-position :

    background-position: right 10px top 50%;
    

    应将背景图像从右侧放置10px,并垂直居中。

        5
  •  -1
  •   Klaus-Dieter Knoll    8 年前

    table.dataTable thead .sorting_asc {
      background: url("http://cdn.datatables.net/1.10.0/images/sort_asc.png") no-repeat 30% 50%;
    }
    table.dataTable thead .sorting_desc {
      background: url("http://cdn.datatables.net/1.10.0/images/sort_desc.png") no-repeat 30% 50%;
    }
    table.dataTable thead .sorting {
      background: url("http://cdn.datatables.net/1.10.0/images/sort_both.png") no-repeat 30% 50%;
    }