position + margin (元素有宽高)
这种方式需要为元素设置宽高,父元素绝对定位,子元素相对定位,margin减去自身宽高的一半
<style>.c {width: 200px;height: 200px;background-color: #ccc;position: absolute;top: 50%;left: 50%;margin-left: -100px;margin-top: -100px;}</style><div class="c"></div>
position + margin (元素无宽高)
这种方式不需要元素设置宽高,父元素绝对定位,子元素相对定位
<style>.c {width: 200px;height: 200px;background-color: #ccc;position: absolute;top: 0;left: 0;right: 0;bottom: 0;margin: auto;}</style><div class="c"></div>
position + transform(元素无宽高)
这种方式不需要元素设置宽高,父元素绝对定位,子元素相对定位
<style>.c {width: 200px;height: 200px;background-color: #ccc;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);}</style><div class="c"></div>
flex布局(元素无宽高)
<style>.f {width: 100%;height: 100%;display: flex;justify-content: center;align-items: center;}</style><div class="f"><div class="c">水平垂直居中</div></div>
