使一个盒子居中有很多种方法,下面是几种比较常用、简单的:
第一种
利用定位和 margin: auto;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>盒子居中第一种</title>
<style>
/* 清楚默认样式 */
* {
margin: 0;
bottom: 0;
}
.father {
/* 给父盒子设置相对定位,子绝父相 */
position: relative;
width: 500px;
height: 500px;
background-color: pink;
}
.son {
/* 给子盒子设定绝对定位,并上下左右都设置为0,再给margin:auto; */
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;