2014-02-24 167 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