text-align:center在CSS中不能垂直工作,我如何解决这个问题? [英] text-align:center doesn't work vertically in CSS, how can I get around this?
问题描述
我正在使用一个只有持有文本的div。它使用绝对定位将自己置于使用相对定位的图像div之上。如果我使用
I'm working with a div that's only holding text. It's using absolute positioning to center itself on top of an image div that is using relative positioning . I can center the div horizontally in CSS if I use
div {
text-align:center;
width:100%;
}
但是当我尝试使用
div {
text-align:center;
height:100%;
}
它不垂直居中。我猜这是因为text-align:center只指定水平..我怎么解决这个问题?我见过一对夫妇的解决方案,如果外div是一个固定的大小,但外div不是一个固定的大小。它是流体,所以我需要这个工作流畅以及。我已经尝试使用顶部:50%但我想它完全居中...我很不熟练,所以容易在我身上
it doesn't vertically center. I'm guessing this is because text-align:center only specifies horizontally.. How could I get around this? I've seen a couple solutions that would work if the outer div is a fixed size, but the outer div is not a fixed size. It's fluid so I need this to work fluidly as well. I've tried using top:50% but I want it perfectly centered... I'm pretty inexperienced so go easy on me
推荐答案
正如你猜到的,你是对的, text-align:center;
用于仅水平而不垂直对齐文本/元素...因此,如果你是谈到要垂直对齐单行文本,您需要使用 line-height
,这将等于容器 height
As you guessed, you are right, text-align: center;
is used to align the text/element horizontally only and not vertically... so if you are talking about aligning the single line text vertically than you need to use line-height
, which will be equal to the container height
div {
height: 100px;
width: 100px;
border: 1px solid #f00;
line-height: 100px;
text-align: center; /* Forgot this in the demo */
}
垂直对齐整个元素,比你可以使用 position:absolute;
,我不建议你,而是使用 display:table-cell; / code>嵌套在
display:table;
parent
Where as if you are looking to vertical align entire element, than you can use either position: absolute;
which I won't suggest you, instead use display: table-cell;
nested inside display: table;
parent
div {
height: 100px;
width: 100px;
border: 1px solid #f00;
display: table;
}
span {
display: table-cell;
vertical-align: middle;
text-align: center;
}
这篇关于text-align:center在CSS中不能垂直工作,我如何解决这个问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!