一.水平垂直居中

1.绝对定位+margin:auto

  1. .box {
  2. width: 500px;
  3. height: 100px;
  4. border: 5px solid black;
  5. position: relative;
  6. }
  7. .box1 {
  8. width: 100px;
  9. height: 80px;
  10. background: red;
  11. margin: auto;
  12. position: absolute;
  13. left: 0; right: 0; top: 0; bottom: 0;
  14. }

2.绝对定位+负margin

  1. .box {
  2. width: 500px;
  3. height: 100px;
  4. border: 5px solid black;
  5. position: relative;
  6. }
  7. .box1 {
  8. width: 100px;
  9. height: 80px;
  10. background: red;
  11. margin: -40px -50px;
  12. position: absolute;
  13. left: 50%;top: 50%;
  14. }

3.绝对定位+transform

  1. .box {
  2. width: 500px;
  3. height: 100px;
  4. border: 5px solid black;
  5. position: relative;
  6. }
  7. .box1 {
  8. width: 100px;
  9. height: 80px;
  10. background: red;
  11. position: absolute;
  12. left: 50%;top: 50%;
  13. transform: translate(-50%,-50%);
  14. }

4.flex布局

  1. .box {
  2. width: 500px;
  3. height: 100px;
  4. border: 5px solid black;
  5. display: flex;
  6. justify-content: center;
  7. align-items: center;
  8. }
  9. .box1 {
  10. width: 100px;
  11. height: 80px;
  12. background: red;
  13. }

二.水平居中

1.行内元素或设置子元素display: inline-block

  1. .box {
  2. width: 500px;
  3. height: 100px;
  4. border: 5px solid black;
  5. text-align: center;
  6. }

2.定宽块级元素

  1. .box {
  2. width: 500px;
  3. height: 100px;
  4. border: 5px solid black;
  5. }
  6. .box1 {
  7. width: 100px;
  8. height: 80px;
  9. background: red;
  10. margin: 0 auto;
  11. }

3.flex

4.绝对定位+负margin

5.绝对定位+transform

6.绝对定位+margin:auto

三.垂直居中

1.单行文本

line-height=height

2.父元素无高度

padding-top=padding-bottom

3.table自带

4.多行文本

父元素display:table,子元素display:table-cell,vertical-align:middle

5.flex

6.绝对定位+负margin

7.绝对定位+transform

8.绝对定位+margin:auto