2016-01-21 36 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%;,否則您將無法看到它。