DIV+CSS如何让文字垂直居中?

如题所述

div+css实现文字垂直居中的五种方法:
1、把文字放到table中,用vertical-align property 属性来实现居中。
<div id="wrapper">
<div id="cell">
<div class="content">Content goes here</div>
</div>
</div>

2、使用绝对定位的 div,把它的 top 设置为 50%,top margin 设置为负的 content 高度。这意味着对象必须在 CSS 中指定固定的高度。
#content {
position: absolute;
top: 50%;
height: 240px;
margin-top: -120px; /* negative half of the height */
}

<div class="content"> Content goes here</div>
3、在 content 元素外插入一个 div。设置此 div height:50%; margin-bottom:-contentheight;。
content 清除浮动,并显示在中间。
<div id="floater">
<div id="content">Content here</div>
</div>

#floater {
float: left;
height: 50%;
margin-bottom: -120px;
}

#content {
clear: both;
height: 240px;
position: relative;
}

4、使用 position:absolute,有固定宽度和高度的 div。这个 div被设置为 top:0; bottom:0;。但是因为它有固定高度,其实并不能和上下都间距为 0,因此 margin:auto; 会使它居中。使用 margin:auto;使块级元素垂直居中即可
<div id="content"> Content here</div>

#content {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
height: 240px;
width: 70%;
}
5、将单行文本置中。只需要简单地把 line-height 设置为那个对象的 height 值就可以使文本居中了。
<div id="content"> Content here</div>

#content {
height: 100px;
line-height: 100px;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-10-05
在说到这个问题的时候,也许有人会问CSS中不是有vertical-align属性来设置垂直居中的吗?即使是某些浏览器不支持我只需做少许的CSS Hack技术就可以啊!所以在这里我还要啰嗦两句,CSS中的确是有vertical-align属性,但是它只对(X)HTML元素中拥有valign特性的元素才生效,例如表格元素中的<td>、<th>、<caption>等,而像<div>、<span>这样的元素是没有valign特性的,因此使用vertical-align对它们不起作用。

CSS网页布局DIV水平居中的各种方法

一、单行垂直居中

如果一个容器中只有一行文字,对它实现居中相对比较简单,我们只需要设置它的实际高度height和所在行的高度line-height相等即可。如:

imoker.cn(爱摩客)提供的代码片段:

div {
height:25px;
line-height:25px;
overflow:hidden;
}
这段代码很简单,后面使用overflow:hidden的设置是为了防止内容超出容器或者产生自动换行,这样就达不到垂直居中效果了。

imoker.cn(爱摩客)提供的代码片段:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "www.w3.org/...al.dtd">
<html xmlns="www.w3.org/1999/xhtml">
<head>
<title> 单行文字实现垂直居中 </title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
body { font-size:12px;font-family:tahoma;}
div {
height:25px;
line-height:25px;
border:1px solid #FF0099;
background-color:#FFCCFF;
}
</style>
</head>
<body>
<div>现在我们要使这段文字垂直居中显示!</div>
</body>
</html>
不过在Internet Explorer 6及以下版本中,这和方法不支持对图片设置垂直居中。本回答被网友采纳
第2个回答  2016-01-09
垂直居中最常用的做法就是通过行高来设置
比如DIV height:100px,,那你再加一个line-height:100px,那这个DIV里的文字就会垂直居中了。。。
相似回答