屏幕窗口居中
- 已知大小的元素在屏幕窗口水平垂直都居中:
元素{ width: 数值+单位; height: 数值+单位; position: fixed; left: 50%; top: 50%; margin-left: -width/2+单位; margin-top: -height/2+单位; }
- 未知大小的元素在屏幕窗口水平垂直都居中
元素{ position: fixed; left: 0; top: 0; right: 0; bottom: 0; margin: auto; }
子元素在父元素内居中
- 已知大小的自元素在父元素内居中:
父元素{ position: relative; } 子元素{ width: 100px; height: 80px; position: absolute; left: 50%; top: 50%; margin-left: -50px; margin-top: -40px; }
- 未知大小的子元素在父元素内居中
第一种:定位
父元素{ position: relative; } 子元素{ position: absolute; left: 0; top: 0; right: 0; bottom: 0; margin: auto; }
第二种:转换为单元格
父元素{ display: table-cell; text-align: center; vertical-align: middle; }
第三种:弹性盒
父元素{ display: flex; justify-content: center; align-items: center; }
第四种:位移
父元素{ position: relative; } 子元素{ position: absolute; left: 50%; top: 50%; transform :translate(-50%,-50%); }
目前学习到的就是这些啦~