CSS中的常见居中布局

1. 水平居中

第一种: margin-left 和 margin-right auto
<div class='test'>
  </div>


设定好宽度和高度后, 左右为间距为auto的时候就可以实现水平居中
.test {
  border: 1px solid red;
  width: 100px;
  height: 100px;
  margin-left: auto;
  margin-right: auto;
}

第二种: flex布局
.test {
  border: 1px solid red;
  width: 100px;
  height: 100px;
  
}

body {
  display: flex;
  justify-content: center;
}

2. 垂直居中


<div class='test'>
  </div>

第一种: 绝对定位
.test {
  border: 1px solid red;
  width: 100px;
  height: 100px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin:-50px 0 0 -50px;
}

第二种: 绝对定位+margin 
.test {
  border: 1px solid red;
  width: 100px;
  height: 100px;
  position: absolute;
  margin: auto;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

3. 文字居中

水平居中
text-align: center;

垂直居中
height: 30px;
line-height: 30px;
  设置完line-height后文字的大小没有改变, 只是文字的上间距和下间距发生了变化
  让文字看上去就是垂直居中


使用flex去做, 只需要在父容器中添加
display: flex;
justify-content: center;
align-items: center;
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容