有一种方法来定位背景图像从其元素的右边一定数量的像素?
例如,要将某个东西从左边定位一定数量的像素(比如10),我是这样做的:
#myElement {
background-position: 10px 0;
}
有一种方法来定位背景图像从其元素的右边一定数量的像素?
例如,要将某个东西从左边定位一定数量的像素(比如10),我是这样做的:
#myElement {
background-position: 10px 0;
}
当前回答
我的问题是,当窗口调整大小时,我需要背景图像与右侧边界保持相同的距离,例如平板电脑/手机等 我的解决方案是像这样使用一个百分比:
background-position: 98% 6px;
它会固定在原地。
其他回答
我发现这个CSS3特性很有用:
/* to position the element 10px from the right */
background-position: right 10px top;
据我所知,IE8不支持这个功能。在最新的Chrome/Firefox中,它工作得很好。
有关受支持的浏览器的详细信息,请参阅我是否可以使用。
使用来源:http://tanalin.com/en/blog/2011/09/css3-background-position/
更新:
现在所有主流浏览器都支持该功能,包括移动浏览器。
如果我明白你的要求你会这样做;
你有一个名为#main-container的DIV容器和其中的。my-element。用这个来开始吧;
#main-container {
position:relative;
}
/*To make the element absolute - floats above all else within the parent container do this.*/
.my-element {
position:absolute;
top:0;
right:10px;
}
/*To make the element apart of elements, something tangible that affects the position of other elements on the same level within the parent then do this;*/
.my-element {
float:right;
margin-right:10px;
}
顺便说一下,如果您在页面中引用较低级别的元素,最好使用类(我假设您因此而更改了上面的名称)。
如果你想使用这个添加箭头/其他图标到一个按钮,那么你可以使用css伪元素?
如果它真的是整个按钮的背景图像,我倾向于将间距合并到图像中,并使用
background-position: right 0;
但如果我必须添加一个设计的箭头到一个按钮,我倾向于有这样的html:
<a href="[url]" class="read-more">Read more</a>
并倾向于用CSS做以下事情:
.read-more{
position: relative;
padding: 6px 15px 6px 35px;//to create space on the right
font-size: 13px;
font-family: Arial;
}
.read-more:after{
content: '';
display: block;
width: 10px;
height: 15px;
background-image: url('../images/btn-white-arrow-right.png');
position: absolute;
right: 12px;
top: 10px;
}
通过使用:after选择器,我使用CSS添加了一个元素来包含这个小图标。您可以通过在a元素中添加span或<i>元素来实现同样的目的。但我认为这是一种向按钮添加图标的更简洁的方式,而且它是跨浏览器支持的。
你可以在这里查看小提琴: http://codepen.io/anon/pen/PNzYzZ
background-position: calc(100% - 8px);
最简单的解决方案是使用百分比。这并不是您想要的答案,因为您要求的是像素精度,但如果您只是需要在右边缘和图像之间有一些填充,那么给出99%的位置通常就足够了。
代码:
/* aligns image to the vertical center and horizontal right of its container with a small amount of padding between the right edge */
div.middleleft {
background: url("/images/source.jpg") 99% center no-repeat;
}