I want to add a margin to the background image so that I distance it from the middle of the screen, but adding it inside that class adds a margin to the whole body.

              body.poppage {     background: url(/Imagenes/tip3.png) 50% 200px no-repeat #E2E4E9; }                          

How could I do it? Thanks

asked Jan 14 '11 at 17:49

6 Answers 6

Use the containers padding to make a kind of margin for the background.

                  <div class="thebox">     <p>HEY!</p> </div>  div.thebox { box-sizing: border-box; width:400px; height:400px;  border: 2px solid #000000; padding: 10px;  background: url(http://studio-creator.com/blog/public/html5.jpg) center; background-size: contain; background-repeat: no-repeat; background-origin: content-box; }                                  

https://jsfiddle.net/gann1pwm/

answered Aug 2 '15 at 22:44

2

  • Very good example background-origin usage! Might be worth adding an explanation on why it's there (to make position relative to content, rather than to the padding edges as would be the default)

    Dec 4 '17 at 15:04

  • This is brilliant, I didn't know about "background-origin: content-box;". Thank you!

    Apr 15 '19 at 16:55

answered Jan 14 '11 at 17:51

2

  • but background position counts pixels necessarily from the left or right of the screen right? There is not way to start counting from the middle?

    Jan 14 '11 at 17:53

  • Create a container with this background, and center it on the page

    Jan 14 '11 at 17:57

this work with me i have 50px navbar

                background-size: contain !important; background-repeat: no-repeat !important; background-position: 0 50px !important;                              

answered May 19 '18 at 20:29

You might want to try something else... like moving the image to the next child. You can make a wrapper div around your fixed-width div to accomplish this task.

answered Jan 14 '11 at 17:54

You can't really add margins to a background image, since it's not actually an element. A couple things you might try:

  1. 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.

  2. If all you want is to make the background image appear to be floating within its container, set its background position.

answered Jan 14 '11 at 17:55

You can add margin (kind of) using this

                background-position-y                              

for y axis (margin-y) and

                background-position-x                              

for x axis (margin-x)

be cautious if you using this for this is still experimental

my instagram @deanpi_ or @alfarisi.milham

answered May 14 at 12:39

Not the answer you're looking for? Browse other questions tagged css or ask your own question.