---
title: "div垂直对齐的实现方案"
author: "javapolo"
date: "2013-08-06T16:53:18Z"
tags: ["CSS", "HTML"]
categories: ["Web前端"]
slug: "div"
draft: false
lastmod: "2013-08-06T16:53:18Z"
id: 1921025
url: "https://javapolo.iteye.com/blog/1921025"
---

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:

This text should be vertically centered, but it's not.

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:

![](/sg/t.gif)This text is vertically centered.

\* 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:

One line of vertically centered text.

One line of vertically centered text.