css盒子怎么垂直居中

2023-12-24 14:30:09 举报文章

CSS盒子垂直居中是前端开发中的一大难点。经常会遇到需要将文本、图片或其它元素垂直居中的需求。下面介绍几种实现方式。

/*1.通过设置行高实现垂直居中*/
.box {
  height: 200px;
  line-height: 200px;
  text-align: center;
}
/*2.通过设置绝对定位*/
.box {
  position: relative;
}
.box .content {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
/*3.通过Flex布局*/
.box {
  display: flex;
  justify-content: center;
  align-items: center;
}
/*4.通过设置table-cell*/
.box {
  display: table-cell;
  vertical-align: middle;
}
 

以上是几种实现CSS盒子垂直居中的方法,不同的情况下选择不同的方式会更加方便和灵活。使用的时候可以根据需要和实际情况进行选择。

如果你认为本文可读性较差,内容错误,或者文章排版错乱,请点击举报文章按钮,我们会立即处理!