Home  >  Article  >  Web Front-end  >  CSS中设置DIV垂直居中的N种方法 兼容IE浏览器

CSS中设置DIV垂直居中的N种方法 兼容IE浏览器

WBOY
WBOYOriginal
2016-07-06 13:28:191331browse

  在说到这个问题的时候,也许有人会问CSS中不是有vertical-align属性来设置垂直居中的吗?即使是某些浏览器不支持我只需做少许的CSS Hack技术就可以啊!所以在这里我还要啰嗦两句,CSS中的确是有vertical-align属性,但是它只对(X)HTML元素中拥有valign特性的元素才生效,例如表格元素中的

、 、等,而像
这样的元素是没有valign特性的,因此使用vertical-align对它们不起作用。

 

Tips: 完美解决方案在文末!

一、单行垂直居中

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

如: 

div {   
height:25px;   
line-height:25px;   
overflow:hidden;   
}

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

<!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>
  <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>

二、多行未知高度文字的垂直居中

  如果一段内容,它的高度是可变的那么我们就可以使用上一节讲到的实现水平居中时使用到的最后一种方法,就是设定Padding,使上下的padding值相同即可。同样的,这也是一种“看起来”的垂直居中方式,它只不过是使文字把

完全填充的一种访求而已。可以使用类似下面的代码: 
div {   
padding:25px;   
} 

  这种方法的优点就是它可以在任何浏览器上运行,并且代码很简单,只不过这种方法应用的前提就是容器的高度必须是可伸缩的。 

<!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>
  <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 {
    padding:25px;
    border:1px solid #FF0099;
    background-color:#FFCCFF;
    width:760px;
  }
  </style>
</head>
<body>
  <div><br />    <pre class="brush:php;toolbar:false">现在我们要使这段文字垂直居中显示!
    

  
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn