Search code examples
htmlcssbackground-image

CSS - how to place a background-image on my background?


I want to display some random design images on my sites background as background-image, problem now is that every time I place such an image it somehow interacts with nearby boxes etc. I just want my design images (small icons etc) to be part of the background without getting in touch with other non-design elements like text, boxes etc.

Something like that I guess:

body {
    min-height: 100vh;
    position: relative;
    height: auto;
    width: auto;
    background-image: url("/static/pattern.jpg");
    background-repeat: repeat;
    z-index: -10;
} -> "The actual background of the site"

.design_element_01 {
    position: relative;
    z-index: -1;
    background-image: url("/static/xyz.png");
    max-width: 100px;
} -> "The design element that should get placed onto the body background from above"

Solution

  • Try:

    .design_element_01 {
      position: absolute
      /*...*/
    }
    

    In addition, you might need to change max-width to width, since a background doesn't provide width to the element.


    Centering the Background

    There are a few different approaches to centering the background. I'll outline one here; if it doesn't work for you, I can describe others.

    Essentially, the idea is to make the .design_element_01 element itself take up the entire page. Then, background-size can be used to constrain the size of the background, and background-position can be used to center it. A basic example would be:

    .design_element_01 {
      position: absolute;
      top: 0;
      left: 0;
      background: url("/static/xyz.png");
      width: 100%;
      height: 100%;
      /* I'm using 100px here since you used max-width: 100px, but you can use whatever you want. */
      background-size: 100px;
      background-position: center;
      background-repeat: no-repeat;
      z-index: -1;
    }
    

    (Do note that I haven't tested this; you may need to tweak it.)

    If you test this example, however, you will notice that this centers the background on the screen, but not necessarily the entire page. This may or may not be what you want. If not, you can change the <body> element's position property:

    body {
      position: relative;
    }
    

    This should cause the .design_element_01 element to be positioned relative to the <body> element.

    I also created a JSFiddle example to demonstrate the solution: https://jsfiddle.net/mouqewzv/.

    Finally, if you don't want your element completely centered, but just offset from the center, you could tweak the left and top properties of design_element_01 to position the background initially at the center, but then offset it.