方法1:宽度和高度已知的
给父元素相对定位
给子元素绝对定位
left: 50%;top: 50%;
margin-left: 负的宽度一半。
margin-top: 负的高度一半;
方法2:宽度和高度自己未知
意思就是说子盒子本身还是有宽度和高度的,只是自己未知。
思路:
给父盒子相对定位
给子盒子绝对定位
top、right、bottom、left全为0
margin: auto;
方法3:flex布局
父元素:display:flex;
子元素可居中
.center{display: flex;justify-content: center;//实现水平居中align-items: center;//实现垂直居中}
方法四:平移 定位+transform
父元素.parent_box{width: 400px;height: 200px;background: red;position: relative;}子元素.child_box{width: 200px;height: 100px;background: #9ff;position: absolute;top: 50%;left: 50%;transform: translate( -50%,-50%);}
方法五:table-cell布局
父级 display: table-cell; vertical-align: middle; 子级 margin: 0 auto;
