元素居中对齐

逸男2022年12月12日
  • CSS
小于 1 分钟

元素居中对齐

块级元素

1.定位法

/* 给需要定位的元素添加 需要父元素开启定位 */
.box {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

2.定位边距法

/* 给需要定位的元素添加 需要父元素开启定位 */
.box {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  margin: auto;
}

3.flex 布局

/* 给父盒子设置 使内部的子元素居中对齐 */
.box {
  display: flex;
  justify-content: center;
  align-items: center;
}

行内元素

text-align: center; /* 给父元素设置 水平居中 */

line-height: 父元素高度px; /* 给需要居中的行内元素设置 垂直居中居中 */
上次编辑于:
贡献者: yinan