一,运用定位(子绝父相)
<style>
.one {
/* 父相 */
position: relative;
width: 600px;
height: 400px;
background-color: #ccc;
}
.two {
/* 子绝 */
position: absolute;
width: 100px;
height: 100px;
background-color: red;
/* 相右和下走父元素的一半 */
left: 50%;
top: 50%;
/* 移动自身的宽高一半 */
margin-left: -50px;
margin-top: -50px;
}
</style>
</head>
<body>
<div class="one">
<div class="two"></div>
</div>
</body>
二,2d平面位移实现居中(translate:translate(x,y))
<style>
.one {
/* 父相 */
position: relative;
width: 600px;
height: 400px;
background-color: #ccc;
}
.two {
/* 子绝 */
position: absolute;
width: 100px;
height: 100px;
background-color: red;
/* 相右和下走父元素的一半 */
left: 50%;
top: 50%;
/* 移动自身的宽高一半 */
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="one">
<div class="two"></div>
</div>
</body>
三,小技巧(子元素必须有宽高)
<style>
.one {
/* 父相 */
position: relative;
width: 600px;
height: 400px;
background-color: #ccc;
}
.two {
/* 子绝 */
position: absolute;
width: 100px;
height: 100px;
background-color: red;
/* 上下左右定位0,加margin:auto; */
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="one">
<div class="two"></div>
</div>
</body>