Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
HTML\CSS:背景图像定位_Html_Css_Positioning_Background Image_Margin - Fatal编程技术网

HTML\CSS:背景图像定位

HTML\CSS:背景图像定位,html,css,positioning,background-image,margin,Html,Css,Positioning,Background Image,Margin,我知道我们可以这样定位 background:url(../images/bg.jpg) top left; 但我想这样做 将背景定位到上止点并向右移动400像素。。。如何做到这一点目前无法使用经典的背景位置符号 您必须使用JavaScript计算元素的宽度并相应地设置位置,或者在图像左侧留出一些透明的空间以将其推到右侧。这可能是最简单的解决方案。可以使用背景剪辑和背景原点来完成,但这是在将来: 包装器DIV或JavaScript应该可以做到这一点。我会尝试使用定位和z-index进行操作。编

我知道我们可以这样定位

background:url(../images/bg.jpg) top left;
但我想这样做


将背景定位到上止点并向右移动400像素。。。如何做到这一点

目前无法使用经典的
背景位置
符号


您必须使用JavaScript计算元素的宽度并相应地设置位置,或者在图像左侧留出一些透明的空间以将其推到右侧。这可能是最简单的解决方案。

可以使用背景剪辑和背景原点来完成,但这是在将来:


包装器DIV或JavaScript应该可以做到这一点。

我会尝试使用定位和z-index进行操作。

编辑:这在IE中很难做到,因此我添加了一些额外的信息,使其也能在IE中工作

Edit2:还使用微软的SuperPreview应用程序在IE6中实现了这一功能。在FF3.6和IE8中测试,以及在SuperPreview中测试IE6

使用以下CSS嵌套对象:

body {
   margin:     0px;
   padding:    0px;
   text-align: center;
}

.parentDiv {
   margin:     0 auto;
   text-align: left;
   width:      2px; /* non-zero width */
}

.childDiv {
   position: relative;
   text-align: left;
   background-image: url("../images/bg.jpg");
   left:   399px !important; /* !important is not honored by IE6 */
   left:   600px;            /* overridden in all but IE6 */
   width:  300px;
   height: 300px;
}
您的代码与此类似(将
DOCTYPE
设置为strict非常重要):


...
子内容

根据图像更改childDiv中宽度和高度的值。

使用Javascript可能更简单

Pseudocode:
    Read the width of the enclosing element
    Compute its center
    Offset the center by desired amount of pixels
    Set this new value as the position of the background image

@JCOC是的,如果你可以使用包装器元素,那么这也是一个好主意。一个额外的元素绝对位于中间,边距将其推到右边。让我们等待Firefox以外的其他浏览器来实现
calc()
,例如,我想这在Firefox中也会起作用:
背景位置:top-moz-calc(50%-400px)。看,这项技术可以工作。。。我自己也会这么做,但这不是解决办法。。。因为您考虑了可变页面高度和跨浏览器解决方案,特别是对于IE5这样的旧浏览器,特别是对于IE6用户占总数的22.5%的国家,我提供的答案是在现代浏览器中工作的。如果您需要IE5/6的特定解决方案,您应该在问题中说明这一点。无论如何,要在这些浏览器中使用它将是一个非常难看的黑客行为。好吧,我用了一份MicrosoftSuperPreview在IE6中测试了这一点。使用这个程序进行测试不是很灵活,但似乎达到了预期的效果。相应地更新答案。我在IE 5.5和IE 7.0中也使用了IETester来确认这一点,但是我无法调整窗口大小以真正验证。我可以声明,每个浏览器的位置完全相同。
Pseudocode:
    Read the width of the enclosing element
    Compute its center
    Offset the center by desired amount of pixels
    Set this new value as the position of the background image