div中的CSS中心文本(水平和垂直) [英] CSS center text (horizontally and vertically) inside a div block
问题描述
我有一个 div
设置为 display:block
。 ( 90px
height
和 width
),我有一些文字里面。
我需要将文本垂直和水平对齐。
我试过 text-align:center
,但它不会执行水平部分,所以我尝试了 vertical-align:middle
但它不工作。
任何想法?
如果它是一行文字和/或图像,那么很容易做到。只需使用
text-align:center;
vertical-align:middle;
line-height:90px; / *与您的div高度相同* /
就是这样。如果它可以是多行,那么它稍微复杂一些。但在 http://pmob.co.uk/ 上有解决方案。寻找垂直对齐。
因为他们往往是黑客或添加复杂的div ......我通常使用一个表格与一个单元格来做到这一点...尽可能简单。
2016/2017年更新:
通常使用 transform
来完成,即使在IE10和IE11等旧版浏览器中也可以正常工作。它可以支持多行文本:
position:relative;
top:50%;
transform:translateY(-50%);
例如: https://jsfiddle.net/wb8u02kL/1/
收缩包裹宽度:
<上面的解决方案使用固定宽度的内容区域。要使用收缩包装宽度,请使用
position:relative;
float:left;
top:50%;
剩下:50%;
transform:translate(-50%,-50%);
例如: https://jsfiddle.net/wb8u02kL/2/
我尝试过flexbox,但它没有得到广泛的支持,因为它会在一些旧版IE如IE10。
I have a div
set to display:block
. (90px
height
and width
) and I have some text inside.
I need the text to be aligned in the center both vertically and horizontally.
I have tried text-align:center
, but it doesn't do the horizontal part so I tried vertical-align:middle
but it didn't work.
Any ideas?
If it is one line of text and/or image, then it is easy to do. Just use
text-align: center;
vertical-align: middle;
line-height: 90px; /* the same as your div height */
that's it. If it can be multiple lines, then it is somewhat more complicated. But there are solutions on http://pmob.co.uk/ Look for "vertical align".
Since they tend to be hacks or adding complicated divs... I usually use a table with a single cell to do it... to make it as simple as possible.
Update for 2016 / 2017:
It can be more commonly done with transform
, and it works well even in older browsers such as IE10 and IE11. It can support multiple lines of text:
position: relative;
top: 50%;
transform: translateY(-50%);
example: https://jsfiddle.net/wb8u02kL/1/
To shrink wrap the width:
The solution above used a fixed width for the content area. To use a shrink wrap width, use
position: relative;
float: left;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
example: https://jsfiddle.net/wb8u02kL/2/
I tried flexbox, but it wasn't as widely supported, as it would break in some older version of IE such as IE10.
这篇关于div中的CSS中心文本(水平和垂直)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!