Vertically centering text using CSSFiled under: CSS Stylesheets
As many people have discovered, there is no CSS definition for vertically centering text in a block element such as a div. One can achieve this in HTML and XHTML, by using a table and the attribute “valign=middle” to vertically center text, however when you want to achieve the same thing in CSS, that’s when it gets quite tricky.
There are a couple work arounds for this problem. Both these work arounds only work for ONE line of text, the solution for multiple lines of text will be posted soon.
Use vertical-align and an invisible image
Use line-height
1. Use vertical-align and an invisible image
Horizontal centering with CSS has been around for a while and can be easily achieved by using “text-align:center”. The closest definition for vertical alignment in CSS is “vertical-align” which may be top, middle or bottom.
vertical-align:top
vertical-align:middle
vertical-align:bottom
The problem with vertical-align is that it’s an inline style, so it won’t vertically center your text in a div when used by itself. For example:
<div style="width:25em; height:10em; border:1px solid #CECECE; vertical-align:middle">
This text should be vertically centered, but it's not.
</div>
This text should be vertically centered, but it’s not.
To use “vertical-align:middle” to center your text, you will need to put an image of the same height as your block element next to the text you want vertically centered. For example:
<div style="width:25em; height:10em; border:1px solid #CECECE">
<img src="/sg/t.gif" alt="" style="width:1px; height:10em; vertical-align:middle" />This text is vertically centered.
</div>*
This text is vertically centered.
* t.gif is a transparent gif of 1 x 1 pixel.
2. Use line-height(最佳)
To use line-height to vertically center text, specify the line-height to be the same height as the block element. For example:
<div style="border:1px solid #CECECE; width:25em; height:10em; line-height:10em">
One line of vertically centered text.
</div>
One line of vertically centered text.
分享到:
相关推荐
Div垂直对齐 CSS+Div 底端对齐 垂直对齐
DIV 垂直居中DIV 垂直居中DIV 垂直居中DIV 垂直居中DIV 垂直居中DIV 垂直居中
div垂直居中屏幕的方法,兼容IE6 7 8 Firefox
该html代码是实现DIV居中及DIV垂直居中的实例,包括: div居中, div内文本居中及垂直居中, div嵌套div并居中, div嵌套div并垂直居中.
div垂直居中的N种方法,div垂直居中的N种方法
CSS解决未知高度的DIV垂直居中CSS解决未知高度的DIV垂直居中
div框水平垂直居中跟内容垂直居中
通过DOM使div左右对齐
ie 火狐兼容而谷歌浏览器不兼容,div水平对齐的解决方式,仅供参考
DIV水平垂直居中,都是利用jquery实现的,很简单
最近项目中碰到的问题,具体代码就不写了,大体说下思路,有两个div,包含关系,图片在小的div中,大的div实现小div垂直居中,或水平,小div再实现另一个方向上的居中就可以了,忘了说了,外面div style="display:...
主要介绍了通过position定位实现div底端对齐,感兴趣的朋友可以参考下
div实现圆角 div实现圆角 div实现圆角 div实现圆角 div实现圆角
div中多行文字垂直居中
本人在面试的时候被问到:如何使一段不定宽高的文字垂直居中呢? 现在来总结一下: 在body中写入结构 <div id=main> <div id=login> djshdk awjdsd sede sfcdf vdj sh dkaw jds dse desf cdf vd jsh dkawjd sds ...
在DIV中图片垂直/水平居中(最简单方法)
自己制作的DIV模态窗口,点击弹出DIV窗口,后层页面屏蔽,实现模态窗口。需要用vs2010打开
DIV和SPAN如何垂直居中对齐,水平居中很简单,设置text-align:center就可以了,垂直居中一直很是疑惑,下面为大家解惑
主要介绍了使用css实现div垂直居中的示例,需要的朋友可以参考下