div垂直对齐的实现方案

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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值