As far as I can tell, it is not possible to place a CSS background image 1em from the right border of any block, neither is it possible to place a image 1em from the bottom.
The following code places the background image 1em from the left and 2em from the top.
<div class="foo" style="background: url('bar.png') no-repeat 1em 2em">
Some text here
</div>
Is there any way in CSS to specify that the background image should be "this far from the right edge" if the size of the box is dynamic and assuming that you cannot change the HTML?
(Percentages won't work, since the box can change size)
If this is not possible, what is the smallest amount of change you need to make to the HTML?
This is the workaround I came up with:
<style>
div.background
{
float: right;
background: url('bar.png') no-repeat top left;
margin-right: 1em;
width: 16px;
height: 16px;
}
</style>
<div class="foo">
<div class="background" style=""> </div>
Some text here
</div>
The most common & simple way to add background image is using the background image attribute inside the <body> tag. The background attribute which we specified in the <body> tag is not supported in HTML5.
You can't really add margins to a background image, since it's not actually an element. A couple things you might try: If you've got a containing element just inside the body, you can apply the background image to this element and set margins on it.
If you need to position a background-image in CSS 20px from the left and 10px from the top, that's easy. You can do background-position: 20px 10px; .
The background-position CSS property sets the initial position for each background image. The position is relative to the position layer set by background-origin .
The CSS3 background-position spec allows you to change the anchor point from the top left to anything you want. For example, the following will set the lower bottom corner of the image 1em from the right and 2px from the bottom:
background-position: right 1em bottom 2px;
Confirmed to work in:
IE9/10, Firefox 13+, Chrome 26+, Opera 11+, Seamonkey 2.14+, Lunascape 6.8.0
As of April 2013, only IE6-8 and some fringe browsers lack support.
Here's a test page: http://jsbin.com/osojuz/1/edit
Elements with position: absolute; can be positioned by their right edge. So, if you don't mind a minor change to the html, do this:
<div id="the-box">
<img id="the-box-bg" src="bar.png" />
Text text text text....
</div>
(...)
#the-box {
position: relative;
}
#the-box-bg {
position: absolute;
right: 1em;
z-index: -1;
}
You could of course also use absolute positioning of a second div, with a repeating background. But then you would have to set the size of the (inner) div in CSS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With