CSS 水平垂直居中总结

169 阅读1分钟

更多详情可见我的CSS 专栏,欢迎 star,一起学习🧐

一、水平居中

1. 行内元素

.item {
  text-align: center
}

2. 块级元素

  • 子元素

    .child {
      margin: 0 auto;
    }
    
  • float 子元素

    .parent {
      width: fit-content;
      margin: 0 auto;
    }
    
    .child {
      float: left;
    }
    

    width: fit-content; 可以让父元素的宽度正好包裹住子元素的宽度

3. Flex Box

.parent {
  display: flex;
  justify-content: center;
}

4. 绝对定位

  • transform

    .box {
      width: 100px;
    	position: absolute;
      left: 50%;
      transform: translate(-50%,0);
    }
    

    父相子绝 + 左边 50% + 左移自身一半宽度

  • left: 50%

    .son {
        position: absolute;
        width: 宽度;
        left: 50%;
        margin-left: -0.5*宽度
    }
    
  • left/right: 0

    .son {
        position: absolute;
        width: 宽度;
        left: 0;
        right: 0;
        margin: 0 auto;
    }
    
    

二、垂直居中

1. 行内元素

.parent {
    height: 高度;
}

.son {
    line-height: 高度;
}

满足两个条件:① 子元素行高 = 父元素行高 ② 单行文本

2. 行内块级+after伪元素

参考张旭鑫大神的文章

.parent {
    width: 300px;
    height: 300px;
    border: 1px solid red;
    text-align: center;
}

.child {
    background: blue;
    width: 100px;
    height: 40px;
    display: inline-block;
    vertical-align: middle;
}

.parent::after {
    content: '';
    height: 100%;
    display: inline-block;
    vertical-align: middle;
}

3. table

.parent {
  display: table;
}
.son {
  display: table-cell;
  vertical-align: middle;
}

4. Flex Box

.box {
  display: flex;
  align-items: center;
}

5. 绝对定位

.son {
    position: absolute;
    top: 50%;
    transform: translate(0, -50%);
}

6. 父相子绝 + margin: auto

 .box1 {
     height: 100px;
     width: 100px;
     position: relative;
}

.child {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}

这里是水平垂直都居中,好用,推荐!相关链接