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

标签 html css

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

#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>

在背景层之上,我想绘制动画层。问题来了:如何将透明动画部分定位到完整(未缩放)背景图像中的特定位置?

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

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

最简单的方法是什么?

最佳答案

根据我的经验,这在纯 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 定位,您可能会希望它是相对的。

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

问题在于上边距和高度百分比,浏览器会从窗口的宽度继承这些值。所以您会注意到,如果您调整 View 窗口的大小,框不会保持完美居中。我过去通常使用 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/

关于html - 定位到父背景上的特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19284214/

相关文章:

javascript - 如何通过 CSS 和 JS 让我的背景图像每 15 秒左右更改一次

css - 具有较低 z-index 的图像继续内容

html - 媒体查询最大宽度 320px 问题

css - 具有绝对位置的div的宽度取决于其父级的宽度?

html - 在 DIV 中使用 iframe 会杀死页面的其余部分

html - 如何最好地在 html 中制作笑脸框

css - Sass编译错误: Can't extend &:before:

javascript - 自定义 Angular 6 Material 日期选择器

android - 为什么我的 WebView 以纯文本 HTML 形式显示 rss?

css - Bootstrap div,右侧带有响应按钮