简体   繁体   English

将元素绝对定位在固定位置的容器内

[英]Absolutely position elements inside a fixed position container

Is it possible to absolutely position elements inside a fixed position container? 是否可以将元素绝对定位在固定位置的容器内? For example: 例如:

<div style="position:fixed; left:0; top:0">
    <div style="position:fixed; left:0; top:0;"></div>
    <div style="position:fixed; left:200px; top:120px;"></div>
</div>

I want to be able to move, using jQuery, the container div to the left and right (and it's children along with it), but this obviously doesn't work (moving the container's left property does not affect the children). 我希望能够使用jQuery将容器div左右移动(以及它的子代),但这显然不起作用(移动容器的left属性不会影响子代)。

I tried something like this: 我尝试过这样的事情:

<div style="position:fixed; left:0; top:0">
    <div style="position:relative; width:100%; height:100%;">
        <div style="position:fixed; left:0; top:0;"></div>
        <div style="position:fixed; left:200px; top:120px;"></div>
    </div>
</div>

...but it doesn't work. ...但是它不起作用。 I know I could ultimately just drop the container and animate each of the fixed position children at the same time, but I'd really prefer not to. 我知道我最终可以放下容器并同时为每个固定位置的孩子设置动画,但是我真的不希望这样做。 I'll probably end up adding more children later, and that would mean managing the animations/movements of each one (now that I think of it, I could just add a class to each child, and have jQuery animate the left property of all occurances of that class, but I'd still prefer to resolve my initial problem if possible). 我可能最终会添加更多的子代,这意味着要管理每个子代的动画/动作(现在我想到了,我可以为每个子代添加一个类,并让jQuery动画化所有子代的left属性。该类的出现,但如果可能的话,我还是更愿意解决我最初的问题)。

Hacks are welcome! 欢迎黑客!

use relative for the children, not fixed. 为孩子使用亲戚,不固定。

<div style="position:fixed; left:0; top:0">
    <div style="position:relative; left:0; top:0;"></div>
    <div style="position:relative; left:200px; top:120px;"></div>
</div>

The children should be position absolute (because they are positioned absolutely within the fixed container). 子项应绝对放置(因为它们绝对位于固定容器中)。

See this demo: http://jsfiddle.net/74dE7/2/ 观看此演示: http : //jsfiddle.net/74dE7/2/

#fixed-box {
    position: fixed;
    height: 300px;
    width: 300px;
    background: red;
    right: 10px;
    top: 10px;
}

#absolute-box {
    position: absolute;
    left: 10px;
    bottom: 10px;
    background: blue;
    height: 50px;
    width: 50px;
}

<div id="fixed-box">
    <div id="absolute-box">
    </div>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM