2014-09-10 150 views
4

我有祖父母需要定位absolute的子元素。问题是父母也绝对定位。绝对父母对祖父母的位置元素

我无法使用JavaScript。我怎样才能用纯粹的CSS来实现呢?

JSFiddle Demo

<div class="col-md-6 gp"> 
    <div class="col-md-4 p"> 
     <div class="col-md-2 c"> position me w.r.t to .gp</div> 
    </div> 
</div> 
.gp { height : 200px; position: relative; } 

.p { 
    height : 100px; width: 250px; 
    position :absolute; 
    top : 50px; left: 50px; 
} 

.c { position: absolute; height: 50px; } 
+0

只需在内部'absolute'元素的周围制作一个包裹'div',并给它'position:relative'。 – Sebsemillia 2014-09-10 14:30:34

+1

请更具体的问题。一个例子会非常好。 – Jason 2014-09-10 14:31:15

+0

@HashemQolami让我感兴趣。坦率地说,如果你的定位是相对于祖父母来说的,那么这是一个争论,把我的想法重新调整,让大孩子成为一个孩子。 – 2014-09-10 14:34:09

回答

21

如果支持Internet Explorer 8(和以下)不是一个问题,我们可以通过纯CSS实现。下面是你应该知道怎么样CSS Transforms

6 The Transform Rendering Model

对于其布局由CSS框模型制约因素,比none在创造 都变换结果的任何 值等一个stacking context和一个containing block。对象 充当包含用于固定位置的后代的块的

因此,我们添加一个transform与其他比auto祖父母元素的值,我们将能够使用fixed定位场所的孩子元素与尊重祖父母元素,它的创建包含块。

EXAMPLE HERE

例如:

.grandpa { 
    position: relative; 
    height: 500px; 

    -webkit-transform: rotate(0deg); 
    -moz-transform: rotate(0deg); 
    -ms-transform: rotate(0deg); 
    -o-transform: rotate(0deg); 
    transform: rotate(0deg); 
} 

.dad { 
    position: absolute; 
    width: 250px; height: 250px; 
    bottom: 4em; left: 4em; 
} 

.son { 
    position: fixed; /* This will be positioned with the respect to the grandpa 
         rather than the viewport */ 
    width: 100px; height: 100px; 
    top: 2em; right: 2em; 
} 

此外,CSS传奇埃里克·梅耶写这个文章:

Un-fixing Fixed Elements with CSS Transforms

变形的元素会创建一个包含块,即使对于已设置为position:fixed的后代 也是如此。换句话说,包含变形元素的固定位置后代的 块是变形元素,而不是视口。

+2

@Hashem - Chrome和其他网络浏览器的浏览器很棒,但是如果我需要在ie9 +中使用它,我该怎么办? – Leann 2015-03-11 17:25:17

+0

@toddmo你是什么意思,当爷爷上下滚动时,它停止工作?看起来儿子和父亲都待在一起。 – 2016-11-22 23:52:56

+0

@IsaacMontaine,我现在在演示中退出了我的评论b/c,它们都在滚动时滚动到一起。 – toddmo 2016-11-23 20:53:25

0

我还没有真正明白你问什么,但我编辑你的CSS:

.gp { 
    height : 200px; 
    border : 1px solid red; 
} 
.p { 
    height : 100px; 
    width: 200px; 
    border : 1px solid blue; 
    position: absolute; 
    top : 50px; 
    left : 50px 
} 
.c { 
    height : 50px; 
    border : 1px solid green; 
    position: absolute; 
    top:0; 
    left:0; 
} 

你写的定位,而不是位置。告诉我,如果它现在可行

+0

看看hasheem的答案,这就是我正在努力实现的目标 – StateLess 2014-09-10 15:02:10

相关问题