Search code examples
htmlcsspadding

How can I pad a background image from the element edge?


I want to add a background image on the right side of the list items, and want to have some padding from the right side as well, but I'm unable to do that. Please have a look at following example:

I know we can set the image position by pixels, but since each of the li has different width, I can't do that.

ul {
  width: 100px;
}

ul li {
  border: 1px solid orange;
  background: url("https://via.placeholder.com/50") no-repeat center right;
}

ul li:hover {
  background: yellow url("https://via.placeholder.com/50") no-repeat center right;
}
<ul>
  <li>Hello</li>
  <li>Hello world</li>
</ul>


Solution

  • You can use percent values for the background-position property:

    background: yellow url("arrow1.gif") no-repeat 95% 50%;
    

    Not pixel perfect, but…