2012-09-28 40 views
1

垂直居中的孩子我有幾個孩子http://jsfiddle.net/thiswolf/FUqSP/父DIV和我想的是含child.For實例中垂直居中子內的每個格我想中心child_twochild_one。我有這個CSS有共同的父

.parent{ 
width:300px; 
height:300px; 
background-color:orange; 
display:table-cell; 
vertical-align:middle; 
} 
.child_one{ 
width:100px; 
height:100px; 
background-color:purple; 
margin-left:auto; 
margin-right:auto; 
} 
.child_two{ 
width:50px; 
height:50px; 
background-color:pink; 
margin-left:auto; 
margin-right:auto; 
} 
.child_three{ 
width:25px; 
height:25px; 
background-color:yellow; 
margin-left:auto; 
margin-right:auto; 
} 
.child_four{ 
width:12px; 
height:12px; 
background-color:red; 
margin-left:auto; 
margin-right:auto; 
} 

,這是HTML

<div class="parent"> 
<div class="child_one"> 
<div class="child_two"> 
<div class="child_three"> 
<div class="child_four"> 
</div> 
</div> 
</div> 
</div> 
</div> 
+1

閱讀此:http://www.vanseodesign.com/css/vertical-centering/它提出了一些很好的方法來實現對中 – Mik378

回答

1

入住這link

我以前float:left;去實現它。

檢查這個fiddle

我已經使用百分比來完成。
對於其他方法來實現這個檢查link

我建議你用百分比來做到這一點。這不會讓你感到困惑。

+0

你應該想出一個正方形的錯覺公式:)。你的解決方案的工作原理,但我不明白你爲什麼浮動:左。 – Gandalf

+0

這樣的margin:top應該被其父div所考慮。你也可以使用'overflow:hidden'。我正在嘗試:) –

0

你可以使用孩子的絕對定位。你必須將每個孩子放在最高50%,剩下50%,並給他們一個寬度和高度的一半的負頂部和左邊界。

.parent{ 
    width:300px; 
    height:300px; 
    background-color:orange; 
    position: relative; 
} 
.child_one{ 
    width:100px; 
    height:100px; 
    background-color:purple; 
    position:absolute; 
    left: 50%; 
    top: 50%; 
    margin-left: -50px; 
    margin-top: -50px; 
} 

這只是第一個孩子。你必須對每個孩子都這樣做。所以如果寬度是50px,請使用-25px的邊距。

http://jsfiddle.net/APdaP/

1

添加這對每個孩子

的位置是:相對的;
top:25%;

這裏完整的CSS,

.parent{ 
width:300px; 
height:300px; 
background-color:orange; 
display:table-cell; 

} 
.child_one{ 
width:100px; 
height:100px; 
background-color:purple; 
margin-left:auto; 
margin-right:auto; 
position: relative; 
top: 25%; 
} 
.child_two{ 
width:50px; 
height:50px; 
background-color:pink; 
margin-left:auto; 
margin-right:auto; 
position: relative; 
top: 25%; 
} 
.child_three{ 
width:25px; 
height:25px; 
background-color:yellow; 
margin-left:auto; 
margin-right:auto; 
position: relative; 
top: 25%; 
} 
.child_four{ 
width:12px; 
height:12px; 
background-color:red; 
margin-left:auto; 
margin-right:auto; 
position: relative; 
top: 25%; 
} 

這裏的DEMO:fiddle

0

據我送你在我以前的評論的鏈接,你應該試着叫了解決方案:

的CSS表法

它會顯示您的divs作爲表格單元格,以便您可以使用vertical-align爲您的子divs。

+0

我現在正在嘗試。當使用表方法http://jsfiddle.net/ thiswolf/Thjbp/ – Gandalf

相關問題