2016-01-21 34 views
1

我想通过translateY来定位父DIV中的子DIV。 但是,如果子DIV不是位置:绝对或没有高度属性的父DIV,它只是用尽父DIV。铬翻译工作不正确

HTML

<div class="parent"> 
    <div class="img-wrap"></div>' 
    <div class="child"></div> 
</div> 

CSS

.parent{ 
    /* 
    height:190px; 
    */ 
    background-color:#ccc; 
    padding:20px; 

    -webkit-transform-style: preserve-3d; 
    -moz-transform-style: preserve-3d; 
    transform-style: preserve-3d; 
} 
.parent:after{ 
    clear:both; 
    content:""; 
    display:block; 
} 
.img-wrap{ 
    background-color:blue; 
    float:left; 
    height:150px; 
    width:200px; 
} 
.child{ 
    background-color:red; 
    height:100px; 
    /* 
    position:absolute; 
    */ 
    position:relative; 
    top:50%; 

    -webkit-transform: translateY(-50%); 
    -ms-transform: translateY(-50%); 
    transform: translateY(-50%); 
} 

这里有一个样本 Position middle vertically

回答

0

下面是你可以做什么,而不是(根据你的下面的评论)。

  • 孩子DIV里面的内容会推到IMG包装的右侧。但它 将叠加在img wrap的顶部,如果我使用位置:绝对

  • 如果我向父级添加固定高度。它会正确定位儿童,但我不能拥有固定的高度,因为img-wrap的高度也不会相同。

  • 不能在子上使用固定宽度,因为img-wrap的宽度将根据div内部的图像而不同。

使用display: table将可以很容易地达到你想要什么。

.parent{ 
 
    background-color:#ccc; 
 
    display: table; 
 
    width: 100%; 
 
} 
 
.img-wrap{ 
 
    display: table-cell; 
 
    background-color:blue; 
 
    height:150px; 
 
    width:200px; 
 
} 
 
.img-wrap2{ 
 
    display: table-cell; 
 
    background-color:blue; 
 
    height:250px; 
 
    width:100px; 
 
} 
 
.child{ 
 
    background-color: red; 
 
    height:100px; 
 
} 
 
.child-wrap{ 
 
    display: table-cell; 
 
    vertical-align: middle; 
 
}
<div class="parent"> 
 
    <div class="img-wrap"></div> 
 
    <div class="child-wrap"> 
 
    <div class="child"></div> 
 
    </div> 
 
</div> 
 
<hr> 
 
<div class="parent"> 
 
    <div class="img-wrap2"></div> 
 
    <div class="child-wrap"> 
 
    <div class="child"></div> 
 
    </div> 
 
</div>

+0

感谢@LSSon,原因是我使用position:relative,因为子DIV内的内容会被推到img wrap的右边。但是如果我使用position:absolute –

+0

,它会覆盖img wrap的顶部,如果向父级添加固定高度。它会正确定位小孩,但我不能拥有固定的高度,因为img-wrap的高度不会相同。 –

+0

@mok_ku我的示例不使用固定高度,因此它将调整大小。 – LGSon

0

此行为是因为.child兄弟.img-wrap的。 当你将位置设置为relative时,它会受到它的兄弟姐妹的影响,所以.img-wrap将影响.child的位置。 正确的行为变化position.childabsolute

+0

感谢@Farzad YZ,位置:绝对将就IMG-包装的顶子DIV覆盖里面的内容,这将使它看起来怪异。 –

+0

如果你想让'img-wrap'来到'child'的顶部,只需要给它添加更高的'z-index'。 –

0

这是你在找什么?

https://jsbin.com/gubefiqohe/edit?css,output

您需要设置.parentposition: relative;并设置.childposition: absolute。您还需要在.child元素上设置width: 100%;,否则您将无法看到它。