Search code examples
cssbackground-imagebackground-position

position background image center bottom with some offset


I would like to position to the bottom of a background image but give it some vertical offset.

Lets say

Same way we can do:

.img{
     background-position: 5px center; /* top + 5px */
}

I tried to:

.img{
     background-position: -5px center; /* bottom - 5px ?? */
}

But the image won't even be visible

How can I achieve this? (without knowing the height of the element).

  • So far I fixed it applying padding (size of image) and margin (offset) to the element with postion:bottom center;

Solution

  • using :before and :after you can achieve the result(use exact location of the sprite image.)

    .img{
        position: relative;
    }
    
    .img:after {
        left: 50%;
        bottom: -5px;
        content: '';
        width: 32px;
        height: 32px;
        margin-left: -16px;
        position: absolute;
        background-position: 0 0;
    }
    
    .img:before {
        left: 50%;
        top: 5px;
        content: '';
        width: 32px;
        height: 32px;
        margin-left: -16px;
        position: absolute;
        background-position: -15px -30px;
    }