2014-02-22 44 views
2

我有一段文字,將改變長度和寬度。如果可能的話,我希望通過css的方式將文本水平和垂直居中,而不管文本的長度是多少。水平和垂直對齊css項目,改變大小

它將永遠在中心。

我知道如果中心文本,如果它不總是通過CSS更改。我可以通過Javascript來形象地做到這一點,但如果有一種方法可以通過CSS來完成,我想知道它。

這是我的示例代碼:

的Html

<h1 id="description">Play</h1> 

CSS

description{ 
     height: 20px; 
     width: 60px; 
     text-align: center; 
     margin: auto; 
     position: absolute; 
     top: 0; left: 0; bottom: 0; right: 0; 
     color: black; 
} 

我的容器爲100%的高度和寬度。

這個CSS顯然不起作用。

小提琴:http://jsfiddle.net/ST59z/

謝謝 利亞姆

+0

添加 – helderdarocha

+0

你想要的'#description'元素在其容器對準一些代碼的例子嗎? –

+0

我所接受的問題的接受答案特別建議對齊容器內部的元素(在本例中爲span或h1)。它還提供了OP可能考慮的更多可能的解決方案。 –

回答

1

爲了在一個未知的尺寸垂直和水平對齊的元素,你可以遵循this approach

在這裏你去:

.container { 
    background-color: gold; 
    height: 300px; 
    text-align: center; /* align the inline(-block) elements horizontally */ 
    font: 0/0 a;   /* remove the gap between inline(-block) elements */ 
} 

.container:before {  /* create a full-height inline block pseudo=element */ 
    content: ' '; 
    display: inline-block; 
    vertical-align: middle; /* vertical alignment of the inline element */ 
    height: 100%; 
} 

#description { 
    display: inline-block; 
    vertical-align: middle; /* vertical alignment of the inline element */ 
    font: bold 36px/1 Arial sans-serif; /* reset the font property */ 
} 

WORKING DEMO

+0

我無法得到這個工作與百分比高度。我正在使用100%的寬度和高度。 –

+0

@LiamShalon元素的百分比高度? –

+0

.container。 –

1

你想這樣的事情還有什麼在小提琴:http://jsfiddle.net/ST59z/9/

代碼:

#description{ 
    height: 20px; 
    width: 60px; 
    text-align: center; 
    margin:auto; 
    position: absolute; 
    vertical-align:middle; 
    top: 0; left: 0; bottom: 0; right: 0; 
    color: black; 
} 

CHANGE:

margin:auto; 
vertical-align:middle; 
+0

html需要垂直對齊。 –

+0

新增了vertical-align:middle now – V31

+0

我在jsFiddle中看不到這個區別。 –

0

這裏有一些變化做:

#description { 
    height: auto; 
    width: auto; 
    text-align: center; 
    max-height:100%; 
    max-width:80%; 
}