css居中

91 阅读1分钟

水平居中:使用text-align: center;来使文本和内联元素水平居中。对于块级元素,可以将其左右外边距设置为auto,例如margin-left: auto; margin-right: auto;来使其在父容器中水平居中。

垂直居中:使用vertical-align: middle;来使内联元素在垂直方向居中。对于块级元素,可以使用flexbox或grid布局来实现垂直居中。示例代码如下:

/* 使用flexbox布局实现垂直居中 */
.container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

/* 使用grid布局实现垂直居中 */
.container {
  display: grid;
  place-items: center; /* 水平和垂直居中 */
}

上下左右居中:使用绝对定位(position: absolute)和top: 50%; left: 50%; transform: translate(-50%, -50%);来实现上下左右居中。这种方法是通过将元素的左上角位置放置在父容器的正中心,并使用translate(-50%, -50%)将元素往左上角偏移自身尺寸的一半,从而实现居中效果。

.container {
  position: relative; /* 父容器设置为相对定位 */
}

.centered-element {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

表格布局(Table Layout):通过将元素放置在表格单元格中,并使用display: table;和相关的表格布局属性来实现居中。

.container {
  display: table;
  width: 100%; /* 父容器宽度设置 */
}

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

使用Flexbox和margin: auto;:使用Flexbox布局,设置align-items: center; justify-content: center;使元素在水平和垂直方向上居中,并将元素的外边距设置为auto来实现自动填充剩余空间。

.container {
  display: flex;
  align-items: center;
  justify-content: center;
}

.centered-element {
  margin: auto;
}