Liangliang Zheng
Liangliang Zheng

Reputation: 1785

How to assign background-position as something like 'margin-right: 10px'?

I am trying to put an image as the background and would like it to align to the right, but not closely align to. Something like margin-right:10px. Is it possible to do that in pure css, without explicitly adding a margin to the image?

I had several attempts, but all failed... http://jsfiddle.net/cA7Un/1/

Thanks in advance!

Upvotes: 1

Views: 254

Answers (2)

David Barnett
David Barnett

Reputation: 196

To use the example you put on jsfiddle:

I declared the following extra style:

.rss
    {
        background-image: url('http://tipabsorb.com/index/wp-content/plugins/category-specific-rss-feed-menu/rss_small_icon.png');
        background-repeat: no-repeat;
        float: right;
        width: 16px;
        min-width: 16px;
        max-width: 16px;
        height: 16px;
        min-height: 16px;
        max-height: 16px;
        margin: 10px;
    }

This uses the same image, but adds an extra div to your your markup. This method gives you the image as a background image, and then with the margin you can position it as far from which ever side you want (by also changing the float if you want it on left hand side).

<div class='test' style='width: 300px; height: 100%'>
    <div class="rss">
    </div>
    <p>
        Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
        euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
</div>

The positioning of the "rss" div before you normal markup is important as this affects the flow. Could also do it by positioning the div absolutely with a relative parent.

Finally I deleted the background from the ".test" class, as it has now been moved to the "rss" class.

I hope this helps.

Upvotes: 0

James Zaghini
James Zaghini

Reputation: 4001

You could use a percentage, but this is only good if you know the width of the container will stay the same:

background-position: 95% center;

Otherwise, you could add 10 pixels of whitespace to the right of your image in an image editor like Photoshop.

enter image description here

Upvotes: 1

Related Questions