有没有一种方法可以相对于元素中心放置背景图像? [英] Is there a way to position a background image relative to the centre of an element?

查看:65
本文介绍了有没有一种方法可以相对于元素中心放置背景图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个元素想要应用背景,尽管我希望背景图像根据其右坐标定位。

I have an element that I wish to apply a background to, though I want the background image to be positioned based on its right co-ordinate.

我可以使用容器div表示背景,尽管在这种情况下并不实际。

I could use a container div to represent the background though it's not really practical in this situation.

我目前有以下规则:

.myelem {
  background-image: url("myelem.png");
  background-position: 5% 60%;
  background-repeat: no-repeat;
}

由于图像的大小,多数情况下可以使用。如果可能的话,我想指定背景的相对位置为中间而不是 left

Which for the most part works because of the size of the image. If it were possible I'd like to have something that specified that the relative position of the background was middle instead of left.

推荐答案

css属性背景位置接受 center 作为值:

The css propoerty background-position accepts center as a value:

.myelem {
    background-image: url("myelem.png");
    background-position: center center;
    background-repeat: no-repeat;
}

或速记版本:

.myelem {
    background: url("myelem.png") center center no-repeat;
}

更新1

没有简单的css方法将背景位置设置为中心(或底部或右侧)的偏移量。

There is no simple css way to set the background-position to an offset of center (or bottom or right).

您可以添加填充到实际图像,使用javascript计算页面加载后的位置,按照以下SO问题中的建议向元素添加边距:

You could add padding to the actual image, use javascript to calculate the position after page load, add margin to the element as suggested in the following SO questions:

  • HTML background image offset by x pixels from the center
  • Offset a background image from the right using CSS

或者,您也可以使用 calc 来计算正确的位置。虽然目前所有浏览器都不支持 calc

Alternatively you can use calc to calculate the correct position. Although calc is not supported by all browsers at this point.

使用calc可以执行以下操作:

Using calc you could do something like this:

.myelem {
    background-image: url("myelem.png");
    background-position: 5% 60%;
    background-position: -webkit-calc(50% - 200px) 60%;
    background-position: calc(50% - 200px) 60%;
    background-repeat: no-repeat;
}

演示

Demo

这篇关于有没有一种方法可以相对于元素中心放置背景图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆