2014-02-22 46 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%; 
}