Languages

CSS - how to make background image position center with 20px offset?

0 points
Asked by:
Kadeem-Craig
516

How can I make background-position: center with 20px offset?

I want to slightly move background image of my element to the top.

1 answer
0 points
Answered by:
Kadeem-Craig
516

Quick solution:

background-position: 50% calc(50% - 20px);

 

Explanation

You can use background-position property with two values to do so, for example:

background-position: center;

is equal to:

background-position: 50% 50%;  /* background-position: position-x position-y; */

Now, what you can do is to use calc() function to create -20px offset for x-axis:

background-position: calc(50% - 20px) 50%;

or y-axis:

background-position: 50% calc(50% - 20px);

Practical example

In the example below, I've created 2 classes (offset-1 and offset-2) that add offset-x and offset-y to the element with bacground image.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    div {
        display: inline-block;
        height: 100px;
        width: 100px;
        border: 1px solid black;

        /* background properties */
        background-image: url('https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png');
        background-size: 50px;
        background-repeat: no-repeat;
    }
    
    .offset-1 {
        background-position: 50% calc(50% - 20px);  /* x-axis: center, y-axis: offset -20px */
    }

    .offset-2 {
        background-position: calc(50% + 20px) 50%;  /* x-axis: offset +20px, y-axis: center */
    }

  </style>
</head>
<body>
  <div class="offset-1"></div>
  <div class="offset-2"></div>
</body>
</html>

 

See also

  1. CSS - custom background image position

  2. CSS - center background image

References

  1. calc() - CSS: Cascading Style Sheets | MDN 
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join