EN
CSS - how to make background image position center with 20px offset?
1
answers
0
points
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
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
References
0 comments
Add comment