定位到父背景上的特定元素

时间:2013-10-09 22:56:50

标签: html css3

我想在HTML5 / CSS3中制作与设备无关的动画。这意味着我有一个背景图像,专门绘制,以便它的边缘可以被切断,我在div元素background-size: cover中使用它,如下所示:

#main-image {
  background: url(intro1-1.jpg) no-repeat center center fixed;
  background-size: cover;
  height: 100%;
  width: 100%;
  overflow: hidden;
  z-index: 0;
}

#propeller {
  background: url(propeller2.png) no-repeat;
  position: relative;
  top: 265px;
  left: 1080px;
  z-index: 10;
  background-size: 100% 100%;
  width: 18%;
  height: 12%;
}

<div id="main-image"><div id="propeller"></div></div>

在背景图层的顶部,我想绘制动画图层。问题就出现了:如何将透明动画部件定位到完整(非缩放)背景图像中的特定位置?

我还需要使用与缩放背景相同的比例来缩放动画图层。但是我该怎么做?

实际上,我正在寻找一种方法来加载高清背景图像,在其上定义高清动画层,然后然后应用cover来填充完整的浏览器屏幕。

最简单的方法是什么?

1 个答案:

答案 0 :(得分:1)

根据我的经验,这在纯CSS中很难做到。我做了类似于你在这里问的事情:http://jsfiddle.net/ahhcE/

这是螺旋桨特定代码:

#propeller {
  background: url(propeller2.png) no-repeat;
  background-color: blue;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-left: -9%;
  margin-top: -6%;
  z-index: 10;
  background-size: 100% 100%;
  width: 18%;
  height: 12%;
}

我将它定位为绝对只是为了方便,但如果它相对于父div定位,你可能会想要它相对。

(对不起颜色,替换你的图片)

问题是在上边距和高度百分比上,浏览器从窗口的宽度继承这些值。因此,您会注意到,如果您调整视图窗口的大小,则框不会保持完全居中。我通常使用javascript解决这个问题。像这样:

function heightAdjust() {
  var windowHeight = $(window).height();
  totalMenuHeight = $("#menu").height();
  document.getElementById('menu').style.marginTop = windowHeight / 2 - totalMenuHeight / 2 + 'px';
  $('.thing').css("height", windowHeight+'px');
}

希望这会有所帮助。垂直居中确实是你唯一的问题,你也可以使用桌面样式成功地破解这个问题,这是一些网站用于垂直定位的。更多相关内容以及此处的其他解决方案:http://coding.smashingmagazine.com/2013/08/09/absolute-horizontal-vertical-centering-css/