Html 将背景图像向右对齐

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4486335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 05:46:57  来源:igfitidea点击:

Aligning background image to right

cssimagehtml

提问by Cyber Junkie

http://jsfiddle.net/Zx836/

http://jsfiddle.net/Zx836/

In the second box, notice how the arrow is in the same place. How can I make it flow with the div?

在第二个框中,注意箭头如何在同一个位置。我怎样才能让它与div一起流动?

Using scroll right centerin the backgroundproperty works but I want to keep some padding right.

scroll right centerbackground属性中使用有效,但我想保留一些正确的填充。

I'm also trying to avoid using 2 divs or the tag. Is this possible just via the .boxdiv?

我也试图避免使用 2 个 div 或标签。这是否可以仅通过 . boxdiv?

采纳答案by Brad Mace

How about adding the image using :afterinstead?

使用:after代替添加图像如何?

.box {
    background: #a6cf83;
    float:left;
    color:#333;
    font-weight:bold;
    padding:8px;
}

.box:after {
    content: url(http://cdn1.iconfinder.com/data/icons/humano2/24x24/actions/new-go-next.png);
}

回答by Ben

.right-align-background {
    background-position: center right;
}

http://jsfiddle.net/Zx836/1/

http://jsfiddle.net/Zx836/1/

回答by oportocala

You could also use background-origin: content-box;if your you would like your background to line up with the padding you set on the element.

background-origin: content-box;如果您希望背景与您在元素上设置的填充对齐,也可以使用。

Something like this:

像这样的东西:

input.error {
 background: no-repeat;
 background-image: url('../images/field-error.png');
 background-position: right center;
 background-origin: content-box;
 padding-right: 5px;
}

回答by Hugo Migneron

If you need padding on the right, I think you might have to go with percentages :

如果您需要在右侧填充,我认为您可能必须使用百分比:

background-position:95% 50%;

will do quite nicely if your elements are of similar width.

如果您的元素具有相似的宽度,效果会很好。

回答by Nick Benson

Calc() has 95% browser support in the US now(September, 2017), and provides an elegant solution to this problem.

Calc() 现在(2017 年 9 月)在美国拥有 95% 的浏览器支持,并为这个问题提供了一个优雅的解决方案。

background-position: calc(100% - 24px) center;