本文共 1138 字,大约阅读时间需要 3 分钟。
四种方式实现水平居中
/* flex弹性布局 父盒子加 弹性元素display: flex 导致的是子盒子的垂直居中*/.box1{ background-color: gray; width: 600px; height: 600px; display: flex; align-items: center; justify-content: center;}.box2{ background-color: hotpink; width: 200px; height: 200px;}
/* 绝对定位 '子绝父相' */.box1{ position: relative; background-color: gray; width: 600px; height: 600px;}.box2{ position: absolute; background-color: hotpink; width: 200px; height: 200px; top: 50%; left: 50%; margin-top: -100px; margin-left: -100px;}
/* 绝对定位 margin: auto */.box1{ position: relative; background-color: gray; width: 600px; height: 600px;}.box2{ position: absolute; background-color: hotpink; width: 200px; height: 200px; /* 设置四个方向为0,就像四个方向有相同的力在拉这个盒子,配上margin:auto让这个盒子的位置保持中立,来使盒子处于正中心 */ top: 0; left: 0; bottom: 0; right: 0; margin: auto;}
/* 绝对定位 位偏移 */.box1{ position: relative; background-color: gray; width: 600px; height: 600px;}.box2{ position: absolute; background-color: hotpink; width: 200px; height: 200px; top: 50%; left: 50%; /* 平移,参考自己的位置来平移 */ transform: translate(-50%, -50%);}
四种方式效果相同,各有优缺,如下图
转载地址:http://yqzki.baihongyu.com/