关于css:css中实现水平垂直居中的5种方法

2次阅读

共计 1737 个字符,预计需要花费 5 分钟才能阅读完成。

  • 办法一:行高法
  • 办法二:内边距法
  • 办法三: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>
正文完
 0