【问题标题】:CSS: Keep a child (img) properly aligned over a background (img)CSS:保持孩子(img)在背景(图像)上正确对齐
【发布时间】:2012-04-19 09:01:14
【问题描述】:

假设我有一个小的透明 gif,我想对齐和缩放一个可以随着浏览器改变大小而缩放的图像。你可能已经猜到了,是的,我想要一个无缝的小动画在照片上,这样照片的一小部分似乎是动画的。

这对于纯 CSS 来说太难了吗?我已经开始用 js 做这件事了,只是用 CSS 看起来很复杂。所以当我继续用代码来做这件事的时候,有没有人碰巧有一种时髦的 CSS 方法?

尝试过这样的事情,但由于某种原因,浮动图像随浏览器(可见)百分比缩放,而不是包含 bg 图像的父 div。

   <div id="bg-image">
        <div class="bg-container">
            <img class="photo" src="../images/bg_artist.jpg" alt=""/>
            <img class="floater" src="../images/twitter.png"  alt="" />
        </div>
    </div>

只是假装我希望子图像显示在右下角:

#bg-image .container 
{
    width:102%;
    margin-left:-10px;
}


#bg-image .photo 
{
    width:102%;
    margin-left:-10px;
}

#bg-image .floater {
    position:fixed; 
    left:90%;
    top:90%;
}

好吧,经过一番折腾,js的解决方案很简单:

var floater = document.getElementById("floater");
var photo = document.getElementById("bg-photo");

floater.style.left = photo.width * .9 +"px";
floater.style.top = photo.height * .5 + "px";

对不起,我会把它放在一个 jsfiddle 中,但它很难处理,因为它涉及整个浏览器。

【问题讨论】:

  • 父div不是随浏览器缩放的吗?然后浮动与容器一起缩放。如果我理解正确,任何演示都将不胜感激;)
  • 好吧,试着提琴
  • Ew。小提琴手很难真正模拟这一点。好吧,父母正在使用图像进行缩放。在这种情况下,它水平拉伸并垂直拉伸以保持纵横比。 .container 的高度实际上比浏览器高。问题是,我的固定位置 div 随着浏览器底部向上移动。我希望它像.photo 一样被切断。让我看看能不能截图

标签: css image alignment scaling


【解决方案1】:

我有点不清楚你希望最终的行为是什么,但this has the images scaling and staying located in relation to each other

HTML

<div id="bg-image">
   <img class="photo" src="path/bkgimage.png" alt=""/>
   <img class="floater" src="path/floatimage.png"  alt="" />
</div>

CSS

#bg-image {
    position: absolute;
    width:100%;
    left: 0;
    top: 0;
}


#bg-image .photo {
    width:100%;
}

#bg-image .floater {
    position:absolute;
    width: 10%;
    height: 10%;
    bottom: 0;
    right: 0;
}

【讨论】:

  • 该死的奇怪。它在测试用例中与这个 css 配合得很好,但我有一些其他元素或 css 干扰。还不能在应用程序中隔离它,但无论如何我都会标记为已回答。在我的情况下,主体已将溢出设置为隐藏,但我在我的测试用例中尝试过它仍然有效......
猜你喜欢
  • 2011-11-10
  • 1970-01-01
  • 1970-01-01
  • 2020-08-08
  • 1970-01-01
  • 2016-12-05
  • 2015-04-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多