Search code examples
cssbackground-position

CSS Background-Position Not Working?


I have the below code and I'm trying to add an attribute to center the background but it's not working.

Existing Code:

<div class="av-section-color-overlay" style="opacity: 1; background-color: #000000; background-image: url(http://andytraph.com/wp-content/uploads/2015/08/avatar.jpg); background-repeat: repeat;"></div>

Existing CSS:

opacity: 1;
background-color: #000;
background-image: url("http://andytraph.com/wp-content/uploads/2015/08/avatar.jpg");
background-repeat: repeat;
}

The CSS I tried to add is:

.av-section-color-overlay {
 background-position: center center !important;
  }

The website is http://andytraph.com/ and I'm trying to center the full-screen Avatar image


Solution

  • There are a few competing problems here:

    1. There is no content inside the element you are working with, so the background image is getting clipped as a result.
    2. The background image is very large, so it is difficult to see the desired centering without either 1) setting the DIV element to a relatively larger height / width, or setting the background-size CSS property.
    3. The concepts of background-repeat: repeat and background-position: center constitute competing desires. You can't really both center an image, and tile it indefinitely in both directions.

    So in light of the above, if you apply a few further style modifications, you get your desired behavior with what you specified: background-position: center. (If you want to center in both directions, you don't need to expressly state it twice -- it is implied that you want to use it in both directions if there is only a single value.)

    Something like:

    .av-section-color-overlay {
        background-color: #000;
        background-image: url("http://andytraph.com/wp-content/uploads/2015/08/avatar.jpg");
        background-repeat: no-repeat;
        background-size: 100px;
        background-position: center;
        height: 200px;
        width: 200px;
    }
    

    and:

    <div class="av-section-color-overlay"></div>
    

    Example: https://jsfiddle.net/7mpqfd22/2/