开发者

How can I position a background-image an absolute distance from the right of its container?

I can position a small background-image/icon 4 pixels from the center left of its container with:

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

How开发者_开发百科 can I position it 4 pixels from the right?


Depending on your situation and what browsers you want to support, this works (tested on 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:

.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%;
}


CSS3 adds a new way to specify background-position:

background-position: right 10px top 50%;

Should position the background-image 10px from the right and vertically centered.


how about

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

in the case you ever want a border


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!)


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%;
}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜