2015-01-06 57 views
0

我正在嘗試使用HTML/CSS,並且在定位時遇到了一些困難。我想要做的是共有12個盒子(3行,每行4個盒子)。第一行將是不同的紅色陰影,第二行將是不同的綠色陰影,而最下面的一行將是不同的藍色陰影。這是代碼,我想出:定位div盒時遇到問題

的HTML/CSS:

.square { 
 
    height: 250px; 
 
    width: 250px; 
 
    border: 1px solid #fff; 
 
} 
 
#red > .square { 
 
    float: left; 
 
    background: #f00; 
 
} 
 
#green > .square { 
 
    float: left; 
 
    background: #0f0; 
 
} 
 
#blue > .square { 
 
    float: left; 
 
    background: #00f; 
 
}
<!DOCTYPE html> 
 
<html lang="en"> 
 

 
<head> 
 
    <meta charset="UTF-8"> 
 
    <title>Color Squares</title> 
 
    <link rel="stylesheet" href="css/style.css"> 
 
</head> 
 

 
<body> 
 
    <main> 
 
    <div id="red"> 
 
     <div class="square sq1"></div> 
 
     <div class="square sq2"></div> 
 
     <div class="square sq3"></div> 
 
     <div class="square sq4"></div> 
 
    </div> 
 
    <div id="green"> 
 
     <div class="square sq1"></div> 
 
     <div class="square sq2"></div> 
 
     <div class="square sq3"></div> 
 
     <div class="square sq4"></div> 
 
    </div> 
 
    <div id="blue"> 
 
     <div class="square sq1"></div> 
 
     <div class="square sq2"></div> 
 
     <div class="square sq3"></div> 
 
     <div class="square sq4"></div> 
 
    </div> 
 
    </main> 
 
</body> 
 

 
</html>

我會在以後改變顏色,現在我更專注於固定定位。我無法在同一行上保留相同的彩色框。我希望第一行是所有的紅色框,但是一些綠色框會到達第一行,一些藍色框會進入第二行。基本上,我需要在每行末尾添加一箇中斷以確保每行都由一種顏色組成。之後,我需要幫助將整個事物垂直和水平居中。我知道垂直居中對CSS有些惱人,但我甚至無法獲得水平居中權(使用margin: auto似乎沒有工作)。任何幫助將非常感激。

回答

1

如果你添加下面的CSS,這是否解決你的問題?

.sq1 { 
    clear: left; 
} 

它告訴每一行的第一個方塊打破前一個浮動流並開始一個新行。

UPDATE:

使其居中,則可以執行以下操作:

main { 
    position: absolute; 
    top: 50%; 
    margin-top: -378px; 
    left: 50%; 
    margin-left: -504px; 
} 

margin-top是(squareHeight +頂邊框寬度+底邊界寬度)* 3個平方/ 2。 margin-left與此類似。下面的文章解釋得非常好,我認爲:http://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/

+0

謝謝修復這些行!現在我只需要弄清楚如何垂直和水平居中整個事情。 – zaynv

+0

由於您明確瞭解所有內容的大小,因此您可以嘗試本文的第一個選項:http://css-tricks.com/centering-in-the-unknown/ – xdhmoore

+0

謝謝!我會看一看。 – zaynv