【前端 | CSS系列】—— 第1篇:如何实现水平垂直居中对齐?

1. 使用【Flex 布局】

.container {
    
    
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

2. 使用【Grid 布局】

.container {
    
    
  display: grid;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

3. 使用【Table 布局】

.container {
    
    
  display: table;
}
.child {
    
    
  display: table-cell;
  text-align: center; /* 水平居中 */
  vertical-align: middle; /* 垂直居中 */
}

4. 使用【绝对定位】+ 【transform 属性】

.container {
    
    
  position: relative;
}
.child {
    
    
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

5. 使用【绝对定位】+ 【margin 属性】 ——(仅适用于:已知元素宽高)

.container {
    
    
  position: relative;
}
.child {
    
    
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -50px 0 0 -50px; /* 其中50px是元素宽高的一半 */
}

单纯的元素左右居中对齐:
块级元素可以使用 magrin: 0 auto;
非块级元素使用 text-align: center;

猜你喜欢

转载自blog.csdn.net/sunshineTing2/article/details/132190156
今日推荐