Setting a margin in a background image

Asked

Viewed 970 times

2

Consider the following html code: http://jsfiddle.net/qt7dsx7b/

In the fiddle a div was defined with an image located in the upper right corner. It turns out I would like to add a margin between the image and the border of the div (simulating a 10px padding in the div). I tried to paddle the div, but the background image doesn’t move. I could also put a background-position: 95% rigth, but in that case I would need to know beforehand the size of the div and the size of the image, and both information I do not possess. The only known information is the 10px space between the image and the border.

  • 2

    Excellent question. This is one of the things effects created by committee (CSS, for example). Guys fill in details they don’t need in the specification, but they don’t think about the obvious things needed in everyday life.

1 answer

3


It’s not quite what you’re asking for, because the CSS is very limited in that respect, but if you have control over the padding of the element, and it is the same as the content of the <div>, one possibility is to use the background-origin to add the value of padding as a margin:

div.box{
    padding:10px;
    background-image: url(/minha/imagem.png);
    background-repeat: no-repeat;
    background-position: right top;
    background-origin: content-box;
}

Support: IE9+ (IE8 depending on usage), Opera 10.5+, Firefox 4+, Webkit (prefixed), Konkeror (prefixed). In Mobile can’t tell the compatibility.

See applied to your JS Fiddle.

  • Interesting this background-origin property. It’s a good way out for my problem.

  • 1

    @Borachio just has to see if the padding will be compatible with the DIV content. There are several other solutions, but without knowing the real case in which it will be applied, I run the risk of proposing something incompatible. If the padding serves, it is the cleanest solution I have seen. Remembering that you can apply 2 different backgrounds or more in recent browsers, and you can specify separately the behavior of each one (one of them taking the whole rectangle, the other with margin). Just separate by comma.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.