1、最开始的时候一直用了比较蠢的方法,在元素外部套一层div,对外部的div设置绝对定位,然后在设置里面的元素margin:0 auto。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<style>
#root{
width: 100%;
height: 100px;
position: relative;
}
.container{
width: 100%;
height: auto;
position: absolute;
left: 0;
top: 40px;
}
.block{
height: 20px;
width: 30px;
position: relative;
margin: 0 auto;
}
</style>
<body>
<div id="root">
<div class="container">
<div class="block"></div>
</div>
</div>
</body>
</html>
2、第二种方法是配合使用left和margin的方法。将left设置为50%,margin-left设置为-width/2,缺点也是显而易见的,需要确切知道元素的宽度
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<style>
#root{
width: 100%;
height: 100px;
position: relative;
background: #eee;
}
.block{
height: 40px;
width: 200px;
position: absolute;
left: 50%;
background: #555;
}
</style>
<body>
<div id="root">
<div class="block"></div>
</div>
</body>
</html>
3、第三种方法,是将left和right同时设置为0,并且设置margin:0 auto.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<style>
#root{
width: 100%;
height: 100px;
position: relative;
background: #eee;
}
.block{
height: 40px;
width: 200px;
position: absolute;
left: 0;
right:0;
margin: 0 auto;
background: #555;
}
</style>
<body>
<div id="root">
<div class="block"></div>
</div>
</body>
</html>
https://blog.youkuaiyun.com/u013050330/article/details/102988218