79

我想在列表项的右侧添加一个背景图像,并希望从右侧也有一些填充,但我无法做到这一点。请看下面的例子:

HTML:

<ul>
    <li>Hello</li>
    <li>Hello world</li>
</ul>

CSS:

ul{
    width:100px;  
}

ul li{
    border:1px solid orange;
    background: url("arrow1.gif") no-repeat center right;
}

ul li:hover{
     background:yellow url("arrow1.gif") no-repeat center right;
}

我知道我们可以按像素设置图像位置,但是由于每个 li 都有不同的宽度,我不能这样做。

这是 JSFiddle 链接:http: //jsfiddle.net/QeGAd/1/

4

9 回答 9

198

您可以使用CSS background-origin更精确:

background-origin: content-box;

这将使图像尊重盒子的填充。

于 2015-08-31T11:14:36.487 回答
56

您可以使用百分比值:

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

不是像素完美,但是……</p>

于 2012-04-17T09:08:31.737 回答
15

使用CSS 背景剪辑

background-clip: content-box;

背景将在内容框中绘制。

于 2016-11-22T13:58:08.293 回答
6

使用background-position: calc(100% - 20px) center,对于像素完美calc()是最好的解决方案。

ul {
  width: 100px;
}

ul li {
  border: 1px solid orange;
  background: url("https://placehold.co/200x125/e16d65/FFFFFF/png") no-repeat calc(100% - 10px) center;
}

ul li:hover {
  background-position: calc(100% - 20px) center;
}
<ul>
  <li>Hello</li>
  <li>Hello world</li>
</ul>

于 2015-12-13T13:28:43.893 回答
4

您可以通过两种方法实现您的结果:-

第一种方法定义位置值:-

HTML

 <ul>
 <li>Hello</li>
 <li>Hello world</li>
 </ul>

CSS

    ul{
    width:100px;    
}

ul li{
    border:1px solid orange;
    background: url("http://www.adaweb.net/Portals/0/Images/arrow1.gif") no-repeat 90% 5px;
}


ul li:hover{
    background: yellow url("http://www.adaweb.net/Portals/0/Images/arrow1.gif") no-repeat 90% 5px;
}

第一个演示:- http://jsfiddle.net/QeGAd/18/

CSS 的第二种方法:before:after选择器

HTML

<ul>
<li>Hello</li>
<li>Hello world</li>

CSS

    ul{
    width:100px;    
}

ul li{
    border:1px solid orange;
}

ul li:after {
    content: " ";
    padding-right: 16px;
    background: url("http://www.adaweb.net/Portals/0/Images/arrow1.gif") no-repeat center right;
}

ul li:hover {
    background:yellow;
}

ul li:hover:after {
    content: " ";
    padding-right: 16px;
    background: url("http://www.adaweb.net/Portals/0/Images/arrow1.gif") no-repeat center right;
}

第二个演示:- http://jsfiddle.net/QeGAd/17/

于 2012-04-17T10:07:02.287 回答
2

使像素完美的唯一选择是在 GIF 本身内创建一些透明填充。这样,您实际上可以将其对齐到 LI 的右侧,并且仍然具有您正在寻找的背景填充。

于 2012-04-17T09:30:27.560 回答
2

您可以将填充添加到游览块元素并添加background-origin样式,如下所示:

.block {
  position: relative;
  display: inline-block;
  padding: 10px 12px;
  border:1px solid #e5e5e5;
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  background-origin: content-box;
  background-image: url(_your_image_);
  height: 14rem;
  width: 10rem;
}

您可以检查几个https://www.w3schools.com/cssref/css3_pr_background-origin.asp

于 2019-06-14T12:48:02.900 回答
0

方向CSS 属性设置为 rtl 应该适合您。我猜IE6不支持它。

例如

<ul style="direction:rtl;">
<li> item </li>
<li> item </li>
</ul>
于 2012-04-17T09:33:23.830 回答
0

添加box-sizing: content-box似乎也有效。请注意,您可能需要调整heightwidthbackground-size,以使用此方法进行填充。

于 2021-08-05T16:56:47.833 回答