2014-10-08 41 views
1

我正在嘗試對齊我網站中的一些圖塊。有4塊瓷磚,第一排有兩個,第二排有兩個。我試圖將這些DIV對齊到頁面的中心,但我無法。Allign Child DIVs to center

我已將margin: 0 auto;添加到父DIV,並且還包括position: relativedisplay: inline-block;,如其他一些帖子所建議的,但尚未能對齊。

下面是我寫的代碼:

<div class="parent"> 
    <div class="child">Child</div> 
    <div class="child">Child</div> 
    <div class="clear"></div> 
    <div class="child">Child</div> 
    <div class="child">Child</div> 
    <div class="clear"></div> 
</div> 

CSS代碼:

.parent{ 
    width: 1000px; 
    margin: 0 auto; 
    position: relative; 
} 
.child{ 
    float: left; 
    margin: 2px auto; 
    width: 25%; 
    background-color: green; 
    position: relative; 
    display: inline-block; 
} 
.clear{ 
    clear: both; 
} 

而且的jsfiddle:http://jsfiddle.net/wj1a2fnj/4/

這一切後,我不能夠將兒童DIV與中心對齊。我是CSS的新手,現在正在思考我的方式。任何幫助將不勝感激。

謝謝。

回答

2

您需要從.child刪除float: left;並添加text-align: center;.parent DIV居中inline-block的孩子裏面的元素。

試試這個 - DEMO

.parent{ 
    width: 1000px; 
    margin: 0 auto; 
    text-align: center; 
    font-size:0; /* to remove the white space between inline-block elements */ 
} 
.child{ 
    display: inline-block; 
    margin: 2px auto; 
    width: 25%; 
    background-color: green; 
    font-size:16px; /* reset the font size (i.e 1em = 16px) */ 
} 

您也可以在第二個孩子後添加<br>標籤,而不是<div>標籤 - http://jsfiddle.net/p6rkw5ax/

0

text-align: center工作

只需將其添加到您的CSS的子類。

http://jsfiddle.net/wj1a2fnj/6/

編輯:

爲什麼它不對齊父div來中心的原因是因爲你使用的浮動。 刪除浮動並調整margin: 0 auto,你會得到你想要的;

更新小提琴:http://jsfiddle.net/wj1a2fnj/19/

+0

我想對齊中心的全格,而不僅僅是文字。我想要做什麼來對齊頁面中心的DIV。即將所有4個圖塊放在頁面的中心,而不僅僅是文本。 – 2014-10-08 09:11:10

0

你可以做這樣的事情......

<div align="center"> 
     <div>whatever you want to align</div> 
    </div> 

只要確保無論你是對準中心擁有相對CSS位置,而不是絕對的或其他任何東西.. 。

1

添加text-align: center;到父div和它的作品

.parent{ 
    width: 1000px; 
    margin: 0 auto; 
    text-align: center; 
    font-size: 0; --> To make the space void in between divs 
} 

地址

.child{ 
    <--float: left;--> REMOVED 
    font-size: 14px; 
    display: inline-block; --> To make the div float next to each other 
} 

WORKING EXAMPLE

0

DEMO

.parent{ 
    width: 1000px; 
    margin: 0 auto; 
    list-style: none; 
    position:relative; 
    text-align: center; 
    vertical-align: middle; 
} 
.child{ 
display: inline-block; 
    margin: 2px auto; 
    width: 25%; 
    background-color: green; 
}