skip to Main Content

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


  1. 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:

    <div class="wrapper">
        <div class="my-icon" data-category="1" style="width: 50%;"></div> <!--image-->
        <div style="width: 50%:">abc</div>
    </div>
    

    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;

    Login or Signup to reply.
  2. 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

    .my-element {
      position: relative;
      display: grid;
      grid-template-columns: 1fr 1fr;
      width: 200px;
      height: 80px;
      
      border: 3px solid black;
      text-align: right;
      padding: 0px 20px 0px 0px;
      font-size: 38px;
    }
    .my-icon {
      color: white;
      font-size: 18px;
    }
    .my-icon[data-category="1"] {
        grid-area: 1/1;
        background-image: url(https://picsum.photos/450/332);
        border: 2px solid green;
        margin: 10px;
    }
    .my-icon[data-category="2"] {
        grid-area: 1/1;
        background-image: url(https://picsum.photos/40/40);
        height: 40px;
        width: 40px;
        border: 2px solid red;
        margin: auto;
    }
    <div class="my-element">
      abc
      <div class="my-icon" data-category="1">def</div>
      <div class="my-icon" data-category="2">ghi</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search