2014-02-24 61 views
2

我在對齊位於div內的<label>時遇到問題。CSS問題:垂直對齊標籤DIV

這裏是我的HTML:

<div class="one-whole index-border"> 
    <div class="score red score--primary"> 
     <label>20</label> 
    </div> 
</div> 

這裏是我的CSS:

.one-whole { 
100%; 
} 
.index-border { 
border-bottom: 2px solid #D2D2D2; 
} 
.score { 
border: none; 
display: inline-block; 
/* margin: 0; */ 
line-height: 1; 
width: 120px; 
height: 100px; 
text-align: center; 
-webkit-border-radius: 6px; 
-moz-border-radius: 6px; 
-ms-border-radius: 6px; 
-o-border-radius: 6px; 
border-radius: 6px; 
-webkit-box-shadow: 0 0 4px rgba(51, 51, 51, 0.125); 
-moz-box-shadow: 0 0 4px rgba(51, 51, 51, 0.125); 
box-shadow: 0 0 4px rgba(51, 51, 51, 0.125); 
color: white; 
margin-bottom: 15px; 
vertical-align: middle; 
} 
.red { 
background: #CC0000; 
background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, #FF3400), color-stop(100%, #CC0000)); 
background-image: -webkit-linear-gradient(#FF3400, #CC0000); 
background-image: -moz-linear-gradient(#FF3400, #CC0000); 
background-image: -o-linear-gradient(#FF3400, #CC0000); 
background-image: linear-gradient(#FF3400, #CC0000); 
} 
.score--primary { 
border: 1px solid #CC0000; 
font-size: 30px; 
font-weight: bold; 
} 

我想用vertical-align: middle會的工作,但沒有運氣。

這裏是一個小提琴:http://jsfiddle.net/oampz/aH86E/

如果有什麼辦法可以重構我的代碼,這將有助於。

感謝

回答

3

你需要display: table-cell;而是採用display: inline-block;

.score { 
    /* Other properties */ 
    display: table-cell; 
} 

Demo


至於代碼的重構的話,你可以放心地爲box-shadow去除對私有性質,box-radius a以及漸變代碼,現在取決於你,直到你想支持舊版瀏覽器的級別。

重構CSS

.one-whole { 
    100%; 
} 

.index-border { 
    border-bottom: 2px solid #D2D2D2; 
} 

.score { 
    border: none; 
    display: table-cell; 
    /* margin: 0; */ 
    line-height: 1; 
    width: 120px; 
    height: 100px; 
    text-align: center; 
    border-radius: 6px; 
    box-shadow: 0 0 4px rgba(51, 51, 51, 0.125); 
    color: white; 
    margin-bottom: 15px; 
    vertical-align: middle; 
} 

.red { 
    background-image: linear-gradient(#FF3400, #CC0000); 
} 

.score--primary { 
    border: 1px solid #CC0000; 
    font-size: 30px; 
    font-weight: bold; 
} 

另外,我剛纔看到你正在使用rgba()所以最好是申報一個回落爲爲好,這樣使用,

.score { 
    /* Other properties */ 
    box-shadow: 0 0 4px #333; /*Equivalent to rgb(51,51,51) */ 
    box-shadow: 0 0 4px rgba(51, 51, 51, 0.125); 
} 
+0

謝謝您的回答,會有什麼影響是擺脫-webkit-邊界半徑:6像素; \t -moz-border-radius:6px; \t -ms-border-radius:6px; \t -o-border-radius:6px; \t border-radius:6px; \t -webkit-box-shadow:0 0 4px rgba(51,51,51,0.125); \t -moz-box-shadow:0 0 4px rgba(51,51,51,0.125); –

+0

@OamPsy如果你在這裏看看,它是舊版本,http://caniuse.com/border-radius所需要的,所以你現在不需要它,因爲用戶不會有那個舊的瀏覽器,即使他們有它,'邊界半徑'將無法正常工作,但會建議您刪除這些 –

4

如果你不想使用table-cell你總是可以設置一個line-height父母。如果我知道容器的高度可能發生變化,我真的更喜歡使用表格單元。

它將允許內容始終居中,在此方法下,您必須更改line-height以匹配容器的高度。

.score{ 
    line-height: 100px; 
} 

Demo