现在的位置: 首页 > 综合 > 正文

css实现文字垂直居中的代码第1/2页

2012年05月01日 ⁄ 综合 ⁄ 共 2015字 ⁄ 字号 评论关闭

CSS中怎样设置才能使对象中的文字垂直居中于对象,这个问题也是捆扰很多朋友的难题。现在网上的很多代码都做不到浏览器兼容。我把网上有关的方法整理了一下,做了些改动,完全可以兼容各主流浏览器。
下面具体说一下在不同情况下垂直居中的方法。
一、一行文字垂直居中
看一下下面的代码:
复制代码 代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>脚本之家-css垂直居中</title>
<script type="text/javascript" language="javascript">
function sel(id) {switch(id) {case "1":document.getElementById("sub").style.lineHeight = "normal";break;case "2":document.getElementById("sub").style.lineHeight = "20px";break;case "3":document.getElementById("sub").style.lineHeight = "28px";break;}}
</script>
<style type="text/css">
#all {
width:240px;
padding:10px;
font-size:12px;
color:#FFF;
background-color:#CCC;
}
#sub {
width:230px;
padding:0 5px;
height:20px;
overflow:hidden;
background-color:#F90;
}
#sel {
margin-top:5px;
}
select {
width:260px;
}
</style>
</head>

<body>
<div id="all">
<div id="sub">一行文字垂直居中,此对象高度为20px</div>
</div>
<div id="sel"><select onchange="sel(this.value)"><option value="1">默认值,设置行高为:normal</option><option value="2">设置行高和对象高度相同:20px</option><option value="3">设置行高比对象的高度大:28px</option></select></div>
</body>
</html>

方法:line-height:20px。设置相同的行高和对象高度。

说明:这种设置简单又兼容各种浏览器,支持内联对象。但如果是固定高度的对象,只能显示一行。当有两行文字时,如果不设置“overflow:hidden”会把对象撑开。
二、多行文字,且高度自适应
请看下面的代码:

xmlns="http://www.w3.org/1999/xhtml">


三行文字垂直居中,设置相同的内上边距padding-top和内下边距padding-bottom就可以。

抱歉!评论已关闭.