likes
comments
collection
share

css中实现水平,垂直居中的5种方法

作者站长头像
站长
· 阅读数 35
  • 方法一:行高法
  • 方法二:内边距法
  • 方法三:CSS3的box方法
  • 方法四: 绝对定位法
  • 方法五:模拟表格法
<!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>DIV中的元素水平垂直居中</title>
<style>
#wrap{width:990px; height:400px;background:#CCCCCC;}
#wrap{position:absolute;left:50%;top:50%;margin-left:-495px;margin-top:-200px}
#wrap2{width:200px; margin:0 auto; padding-top:35px;}


/*方法一:行高法*/
#box{ width:200px; height:50px; background: #FFCC00;margin-bottom:20px; position:relative; font-size:16px;}
.box1{line-height:50px; text-align:center;}

/*方法二:内边距法*/
.box2{width:200px;font-size:16px; background:#FFCC00; margin:20px 0;} 
.box2{text-align:center; padding:16px 0px;}

/*方法三:CSS3的box方法*/
.box3{
    justify-content:center; align-items:center; 
    display: -webkit-box;
    -webkit-box-orient: horizontal;
    -webkit-box-pack: center;
    -webkit-box-align: center;

    display: -moz-box;
    -moz-box-orient: horizontal;
     -moz-box-pack: center;
    -moz-box-align: center;

    display: -o-box;
    -o-box-orient: horizontal;
    -o-box-pack: center;
     -o-box-align: center;

    display: -ms-box;
    -ms-box-orient: horizontal;
    -ms-box-pack: center;
    -ms-box-align: center;

    display: box;
    box-orient: horizontal;
    box-pack: center;
    box-align: center;
}


/*方法四:绝对定位法*/
.div4{position: absolute;left: 50%;top:50%;display:block;margin-top:-8px;margin-left:-40px;}


/*方法五: 模拟表格法*/
.div5{display:table;}
.div5a{display:table-cell; vertical-align:middle; text-align:center;}
</style>
</head>


<body>
<div  id="wrap">
    <div id="wrap2">
        <div id="box" class="box1">行高法居中</div>
        <div  class="box2">内边距法居中</div>
        <div id="box" class="box3">CSS3中的box法</div>
        <div id="box" ><span class="div4">绝对定位法<span></div>
        <div id="box" class="div5" ><div class="div5a">模拟表格</div></div>
</div>
</div>
</body>
</html>