2016-05-13 74 views
2

height屬性我有這樣的:CSS少 - 獲取當前類

.class { 
    height:10px; 
    padding:2px; 
    box-sizing:border-box; 
} 

.class .subclass { 
    height:100%; 
    line-height:???; 
} 

正如你可以看到class有一個固定的高度,但subclass有一個相對百分比高度。這個高度儘管值爲100%,但並不等於父母的身高,因爲它受父母的padding屬性的影響。我需要的是設置line-height屬性等於height屬性,以垂直居中文本。

問題: 我怎樣才能得到當前類的高度以較少的(我們設置line-height屬性的類)?

我知道我可以設置變量,然後做一個計算,這樣一來:

@class-height:10px; 
@class-padding:2px; 
@subclass-height:calc(@class-height - @class-padding * 2); //*2 because of Top & bottom padding 

.class { 
    height:@class-height; 
    padding:@class-padding; 
    box-sizing:border-box; 
} 

.class .subclass { 
    height:@subclass-height; 
    line-height:@subclass-height; 
} 

但我想知道如果有一個簡單的方法來實現這一目標,而不計算和固定變量的設置。

+0

[This](https://jsfiddle.net/pt366e9k/)是一種不使用'line-height'來實現垂直居中的可能方法。我沒有意識到任何缺點,我認爲這可能對你有用。 (*我已經改變了父母的「身高」,只是爲了顯示父母的身高改變時文字如何居中。*) – Harry

回答

2

如果父母高度是一個固定的數字,您可以使用絕對定位。

.parent{ 
    height: 100px; 
    background-color: tomato; 
    width: 100%; 
} 

.child{ 
    position: relative; 
    left: 0; 
    right: 0; 
    margin: 0 auto; 
    top: 50%; 
    transform: translateY(-50%); 
    text-align: center; 
} 

另一種選擇是利用vertical-align屬性爲table所以你可以寫你的CSS這樣。

.parent{ 
    height: 100px; 
    background-color: tomato; 
    width: 100%; 
    display: table; 
    text-align: center; 
} 

.child{ 
    display: table-cell; 
    margin: 0 auto; 
    text-align: center; 
    vertical-align: middle; 
} 
+0

這些都是很好的方法!順便說一下,我仍然對LESS的選項感興趣。謝謝 ;) – ProtectedVoid