<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>元素上下左右居中</title>
<style type="text/css">
*{margin:0;padding:0;}
.temp{margin:15px auto;border:1px solid red;width:100px;height:100px;background-color:red;}
</style>
</head>
<body>
<p>已知父子元素大小,并利用最基本的控制</p>
<style type="text/css">
#temp1-son{margin:25px auto;width:50px;height:50px;background-color:blue;}
</style>
<div id="temp1" class="temp">
<div id="temp1-son"></div>
</div>
<p>根据定位:已知子级元素大小情况</p>
<style type="text/css">
#temp2{position:relative;}
#temp2-son{top:25px;left:25px;width:50px;height:50px;background-color:blue;position:absolute;}
</style>
<div id="temp2" class="temp">
<div id="temp2-son"></div>
</div>
<p>根据css3属性:flex:</p>
<style type="text/css">
#temp3{display:flex;align-items:center;justify-content:center;}
#temp3-son{width:50px;height:50px;background-color:blue;}
</style>
<div id="temp3" class="temp">
<div id="temp3-son"></div>
</div>
<p>根据translate:</p>
<style type="text/css">
#temp4-son{top:50%;left:50%;width:50px;height:50px;background-color:blue;position:relative;
-moz-transform: translate(-50%,-50%);
-webkit-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
-o-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);}
</style>
<div id="temp4" class="temp">
<div id="temp4-son"></div>
</div>
<p>第五种:</p>
<style type="text/css">
#temp5{position:relative;}
#temp5-son{left:0; right: 0; margin:25px auto;width:50px;height:50px;background-color:blue;position:absolute;}
</style>
<div id="temp5" class="temp">
<div id="temp5-son"></div>
</div>
</body>
</html>
五种 css 让元素上下 左右 居中方法
最新推荐文章于 2024-02-27 16:25:30 发布