css div水平居中与垂直居中多个例子

发布时间:2020-07-16编辑:脚本学堂
本文介绍了css实现div水平居中与垂直居中的几个例子,包括未知宽度水平居中、未知宽高div水平与垂直居中、已知宽高div 水平垂直居中等多种情况,需要的朋友参考下。

一、未知宽度水平居中
 

复制代码 代码示例:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>未知宽高div在页面内水平垂直居中 - www.plcxue.com</title>
<style>
*{margin:0; padding:0;}
body,html{overflow:hidden; height:100%;}
.box {height: 100%; overflow: hidden; position: relative; width: 100%; display: table;}
.middle {top:50%;text-align:center;display: table-cell; vertical-align: middle; *position:absolute; *left:50%;}
.content{border:#09F solid 1px; margin:0 auto; position:relative; top:-50%;font:12px/2 "Microsoft YaHei"; padding:0 10px; display:table; *left:-50%;}
</style>
</head>
<body>
<div class="box">
 <div class="middle">
 <div class="content">未知宽高div在页面内水平垂直居中</div>
</div>
</div>
</body>
</html>
 

 
二、未知宽高div 水平垂直居中
 

复制代码 代码示例:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>未知宽高div在页面内水平垂直居中</title>
<style>
*{margin:0; padding:0;}
body,html{overflow:hidden; height:100%;}
.box {height: 100%; overflow: hidden; position: relative; width: 100%; display: table;}
.middle {top:50%;text-align:center;display: table-cell; vertical-align: middle; *position:absolute; *left:50%;}
.content{border:#09F solid 1px; margin:0 auto; position:relative; top:-50%;font:12px/2 "Microsoft YaHei"; padding:0 10px; display:table; *left:-50%;}
</style>
</head>
<body>
<div class="box">
 <div class="middle">
  <div class="content">未知宽高div在页面内水平垂直居中</div>
</div>
</div>
</body>
</html>

三、已知宽高div 水平垂直居中

复制代码 代码示例:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>宽高固定的容器如何在浏览器中水平垂直居中</title>
</head>
<style>
html,body { margin:0; padding:0; height:100%; font:12px/180% "宋体"; text-align:center;}
#main {
 width:200px;
 height:20px;
 background-color:#ddd;
 position:relative;
 top:50%;
 margin:-10px auto 0 auto;   
 /*   margin-top=-(height/2);   */
}
</style>
<body>
<div id="main">
水平及垂直居中
</div>
</body>
</html>