I’d like to align image files (as .png
) with an offsetted image center axis using CSS’s background-
*-properties.
Imagine having the following document:
<div class="my-icon" data-category="1">abc</div>
<div class="my-icon" data-category="2">def</div>
<div class="my-icon" data-category="1">ghi</div>
with the following style sheet:
.my-icon {
background-position: center left;
background-repeat: no-repeat;
background-size: contain;
padding-left: 25px;
height: 30px;
display: flex;
}
.my-icon[data-category="1"] {
background-image: url('...../icon-1.png');
}
.my-icon[data-category="2"] {
background-image: url('...../icon-2.png');
}
I can align the icon as follows:
background-position: center center; |
background-position: center left; |
---|---|
However, what I want is the following:
I’d like the image’s center axis to be aligned with an axis offsetted by x
pixels from the left-hand side of the div
.
How is this feat achievable using pure CSS? (Without JS/JQuery?)
2
Answers
I would post a reply, as this is not actually an answer, but I don’t have enough rep…
If you have the possibility of editing the HTML, I would suggest doing something like this:
use classes instead of inline css ofcourse.
Otherwise here is an example of setting offset with percentages and statements (left, right). So something along the lines of
background-position: 50% center;
Your HTML and CSS seems incomplete. I assume your icons are wrapped in a parent element, so I wrapped your icons in a
.my-element
div.Using background-image to position elements and their backgrounds relative to a parent is very tricky. I would suggest using CSS Grid to position icons. Here’s an example using
display: grid