公共部分, 一共有7种方法
<style>* {box-sizing: border-box;padding: 0;margin: 0;}body {width: 100%;height: 100%;}/* 待补充 */</style><body><div></div></body>
定位+位移
div {position: absolute;width: 100px;height: 100px;top: 50%;left: 50%;transform: translate(-50%, -50%);background-color: red;margin: auto;}
定位 + margin=auto方法
div {position: absolute;top: 0;left: 0;bottom: 0;right: 0;width: 100px;height: 100px;margin: auto;background-color: red;}
定位+margin(top, left一半)
div {position: absolute;top: 50%;left: 50%;width: 100px;height: 100px;margin: -50px 0 0 -50px;background-color: red;}
flex方法
body {width: 100%;height: 100vh;/* 这里需要设置页面的高度为100vh,元素会被撑开屏幕高度一致 */display: flex;justify-content: center;align-items: center;overflow-y: hidden;}div {width: 100px;height: 100px;background-color: red;}
text-center和line-height方法
body {width: 100%;height: 100vh;line-height: 100vh;text-align: center;}div {display: inline-block;width: 100px;height: 100px;background-color: red;}
定位+calc方法
div {position: absolute;width: 100px;height: 100px;top: calc(50% - 50px);left: calc(50% - 50px);background-color: red;margin: auto;}
grid方法
align-items属性控制垂直位置,justify-items属性控制水平位置. 这两个属性的值一致时, 就可以合并写成一个值. 所以,place-items: center; 等同于place-items: center center;
body {width: 100%;height: 100vh;display: grid;place-items: center;}div {width: 100px;height: 100px;background-color: red;}
