ChatGPT解决这个技术问题 Extra ChatGPT

Offset a background image from the right using CSS

css

Is there a way to position a background image a certain number of pixels from the right of its element?

For example, to position something a certain number of pixels (say, 10) from the left, this is how I'd do it:

#myElement {
    background-position: 10px 0;
}
You surely don't mean background-position: -10px 0;? Just checking :)
I know this has a number of duplicates but I'm unable to find any of them.
@thirtydot that moves it 10 pixels left from the left edge.
its stupid that it isnt available...
@nickf you do realize it wasnt available in most devices by the end of 2013 right?

J
James Douglas

I found this CSS3 feature helpful:

/* to position the element 10px from the right */
background-position: right 10px top;

As far as I know this is not supported in IE8. In latest Chrome/Firefox it works fine.

See Can I use for details on the supported browsers.

Used source: http://tanalin.com/en/blog/2011/09/css3-background-position/

Update:

This feature is now supported in all major browsers, including mobile browsers.


This is great but unfortunately it does not work on Safari 5.1.7 (which is extremely important if viewed by mobile phones)
It works now on mobile devices (checked on Android, iOS and WindowsPhone). Still Safari 5.1.7 not support background position given like here.
I'm using this but with a percentage fallback for older browers, eg. background-position: 95% center; background-position: right 13px center;
Not sure how many people are still using browsers old enough not to support this. Safari users should be on a newer version by now, although a lot of older android devices are still out there. caniuse.com/#feat=css-background-offsets Easy enough to use a percentage fallback for these (although it isn't exactly the same).
Please note that this only works if you specify a cardinal position for both vertical and horizontal position such as right left top bottom. For example, the following will not render: background-position: right 10px 10px but should be written as background-position: right 10px top 10px
2
2 revs, 2 users 84%

!! Outdated answer, since CSS3 brought this feature

Is there a way to position a background image a certain number of pixels from the right of its element?

Nope.

Popular workarounds include

setting a margin-right on the element instead

adding transparent pixels to the image itself and positioning it top right

or calculating the position using jQuery after the element's width is known.


More comprehensive support for the extended CSS3 'background-position' is just around the corner: stackoverflow.com/questions/501375/…
M
Matt Brock

The easiest solution is to use percentages. This isn't exactly the answer you were looking for since you asked for pixel-precision, but if you just need something to have a little padding between the right edge and the image, giving something a position of 99% usually works well enough.

Code:

/* aligns image to the vertical center and horizontal right of its container with a small amount of padding between the right edge */
div.middleleft {
  background: url("/images/source.jpg") 99% center no-repeat;
}

+1 "We'll go through pixel alignment next week" - always works.
This solution seems to work most consistently across browsers.
T
Tami

Outdated answer: It is now implemented in major browsers, see the other answers to this question.

CSS3 has modified the specification of background-position so that it will work with different origin point. Unfortunately, I can't find any evidence that it is implemented yet in any major browsers.

http://www.w3.org/TR/css3-background/#the-background-position See example 12.

background-position: right 3em bottom 10px;

Thanks Tami! Unfortunately, this didn't work for me in either Firefox 4 or Chrome 11.
This is implemented in Opera. Thought it was too good to be true and then I tested in other browsers and I was right.
This still doesn't work in current version of Chrome. Version 21.0.1180.89
Chrome Canary (v26) now supports this. Once that trickles down to the release channel, and Safari updates their engine, only IE6-8 will lack support (IE9/10 already support the new format).
Just tested this, and it's now working in Firefox (v.18.0.2), IE (v.9.0.8) and Chrome (v.25.0.1364.97), but it's not yet working in Safari (v.5.1.2). Would love to know if anyone knows when that may be rolled out ;-)
C
Community

As proposed here, this is a pretty cross browser solution that works perfectly:

background: url('/img.png') no-repeat right center;
border-right: 10px solid transparent;

I used it since the CSS3 feature of specifying offsets proposed in the answer marked as solving the question is not supported in browsers so well yet. E.g.


What about when I need that border to be of a certain color?
This is a great answer because you can have pixel precision while keeping it cross-browser compatible. Thanks! (And if you want a border that's a certain color, use a wrapper of some type to wrap the input and add the border to that element.)
C
Community

The most appropriate answer is the new four-value syntax for background-position, but until all browsers support it your best approach is a combination of earlier responses in the following order:

background: url(image.png) no-repeat 97% center; /* default, Android, Sf < 6 */
background-position: -webkit-calc(100% - 10px) center; /* Sf 6 */
background-position: right 10px center; /* Cr 25+, FF 13+, IE 9+, Op 10.5+ */

M
Merosi

A simple but dirty trick is to simply add the offset you want to the image you are using as background. it's not maintainable, but it gets the job done.


N
Novocaine

This will work on most modern browsers...apart from IE (browser support). Even though that page lists >= IE9 as supported, my tests didn't agree with that.

You can use the calc() css3 property like so;

.class_name {
    background-position: calc(100% - 10px) 50%;
}

For me this is the cleanest and most logical way to achieve a margin to the right. I also use a fallback of using border-right: 10px solid transparent; for IE.


This is great but unfortunately it does not work on Safari 5.1.7 (which is extremely important if viewed by mobile phones)
Then you should use a background-position that works in Safari, and one that can be overridden by browsers that can use it. For example: background-position: 92% 8px; background-position: calc(100% - 12px) 8px;
Does not work on all browsers dude. The right 10px center syntax has more extended support in browsers.
Please read the first line where I state this works on "most modern browsers". I never said it works on all of them.
According to caniuse, the use of a calc would crash IE9 ... once you replaced the _ with a -
J
Jonatas Walker

Ok If I understand what your asking you would do this;

You have your DIV container called #main-container and .my-element that is within it. Use this to get you started;

#main-container { 
  position:relative;
}
/*To make the element absolute - floats above all else within the parent container do this.*/
.my-element {
  position:absolute;
  top:0;
  right:10px;
}

/*To make the element apart of elements, something tangible that affects the position of other elements on the same level within the parent then do this;*/
.my-element {
  float:right;
  margin-right:10px;
}

By the way, it better practice to use classes if you referencing a lower level element within a page (I assume you are hence my name change above.


T
Tom Gaulton

The CSS3 specification allowing different origins for background-position is now supported in Firefox 14 but still not in Chrome 21 (apparently IE9 partly supports them, but I've not tested it myself)

In addition to the Chrome issue that @MattyF referenced there's a more succinct summary here: http://code.google.com/p/chromium/issues/detail?id=95085


I just tested this, and it's now working in Firefox (v.18.0.2), IE (v.9.0.8) and Chrome (v.25.0.1364.97), but not in Safari (v.5.1.2)
N
Nighto

If you have proportioned elements, you could use:

.valid {
    background-position: 98% center;
}

.half .valid {
    background-position: 96% center;
}

In this example, .valid would be the class with the picture and .half would be a row with half the size of the standard one.

Dirty, but works as a charm and it's reasonably manageable.


In my case (using a fixed width layout) this does exactly what I need. Thanks.
S
Stijn_d

If you would like to use this for adding arrows/other icons to a button for example then you could use css pseudo-elements?

If it's really a background-image for the whole button, I tend to incorporate the spacing into the image, and just use

background-position: right 0;

But if I have to add for example a designed arrow to a button, I tend to have this html:

<a href="[url]" class="read-more">Read more</a>

And tend to do the following with CSS:

.read-more{
    position: relative;
    padding: 6px 15px 6px 35px;//to create space on the right
    font-size: 13px;
    font-family: Arial;
}

.read-more:after{
    content: '';
    display: block;
    width: 10px;
    height: 15px;
    background-image: url('../images/btn-white-arrow-right.png');
    position: absolute;
    right: 12px;
    top: 10px;
}

By using the :after selector, I add a element using CSS just to contain this small icon. You could do the same by just adding a span or <i> element inside the a-element. But I think this is a cleaner way of adding icons to buttons and it is cross-browser supported.

you can check out the fiddle here: http://codepen.io/anon/pen/PNzYzZ


that should be content: ''; rather than content:0; but this was a useful solution for me
Z
Zeal Murapa
background-position: calc(100% - 8px);

A
André Figueira

use center right as the position then add a transparent border to offset it?


That's not bad, but then the content would also be shifted in from the right. This may or may not be a dealbreaker. Here's an example of how it looks: jsbin.com/ijewoq/1
Think it's just a case of balancing with a little trial and error :) hope it works out!
J
Julix

If you have a fixed width element and know the width of your background image, you can simply set the background-position to : the element's width - the image's width - the gap you want on the right.

For example : with a 100px-wide element and a 300px-wide image, to get a gap of 10px on the right, you set it to 100-300-10=-210px :

#myElement {
  background:url(my_image.jpg) no-repeat -210px top;
  width:100px;
}

And you get the rightmost 80 pixels of your image on the left of your element, and a gap of 20px on the right.

I know it can sound stupid but sometimes it saves the time... I use that much in a vertical manner (gap at bottom) for navigation links with text below image.

Not sure it applies to your case though.


J
JC_Dev

my problem was I needed the background image to stay the same distance from the right border when the window is resized i.e. for tablet / mobile etc My fix is to use a percenatge like so:

background-position: 98% 6px;

and it sticks in place.


That might work in situations where you know exactly the dimensions of the window, but for most of the time on the web, you can't be sure of that. Take a look at the accepted answer which will work in all situations (on supported browsers).
D
David Jazzy Dawson

yes! well to position a background image as though 0px from the right-hand side of the browser instead of the left - i use:

background-position: 100% 0px;