CSS 如何将背景图像定位到与其容器右侧的绝对距离?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3319514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I position a background-image an absolute distance from the right of its container?
提问by Eric
I can position a small background-image/icon 4 pixels from the center left of its container with:
我可以将一个小的背景图像/图标放置在距离容器左中心 4 个像素的位置:
background: url(...) no-repeat 4px 50%;
How can I position it 4 pixels from the right?
我怎样才能将它定位在距离右侧4 个像素的位置?
回答by ScottS
Depending on your situation and what browsers you want to support, this works (tested on IE7-8, Firefox):
根据您的情况和您想要支持的浏览器,这有效(在 IE7-8、Firefox 上测试):
background: url(...) no-repeat right 50%; border-right: 4px solid transparent;
Of course, if you are already putting a border on the right, this will not help you at all.
当然,如果您已经在右侧放置了边框,则这根本无济于事。
Added on edit:If the above doesn't work because your are using the border, and you don't care about IE7 (not sure we are quite at that point yet), and your "icon" width is known, then you could do:
在编辑时添加:如果由于您正在使用边框而上述内容不起作用,并且您不关心 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%;
}
回答by isildur4
how about
怎么样
background: url(...) no-repeat right 50%;
padding:0px;
padding-right:4px;
in the case you ever want a border
如果你想要一个边框
回答by Pekka
I'm afraid you can't as far as I know.
就我所知,恐怕你不能。
Popular tricks:
流行的技巧:
Adding a 4px transparent margin to the image and giving it
background-position: right
Adding a 4px
margin-right
to the element (works in some situations, doesn't in others)Using jQuery to determine the element's weight and adjust the image position (yuck!)
为图像添加 4px 透明边距并赋予它
background-position: right
向
margin-right
元素添加 4px (在某些情况下有效,在其他情况下无效)使用 jQuery 确定元素的权重并调整图像位置(糟糕!)
回答by Eric
CSS3 adds a new way to specify background-position
:
CSS3 添加了一种新的指定方式background-position
:
background-position: right 10px top 50%;
Should position the background-image 10px from the right and vertically centered.
应将背景图像放置在距离右侧 10 像素且垂直居中的位置。
回答by Klaus-Dieter Knoll
You might want to use percentage:
您可能想使用百分比:
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%;
}