0
点赞
收藏
分享

微信扫一扫

CSS居中的集中常用方法

JakietYu 2022-05-01 阅读 91
  1. text-align: center;
<div class="center1">
  <span>111</span>
</div>

.center1 {
  text-align: center;
}
  1. margin: 0 auto;
    (需要先制定一个宽度,让块级元素居中,然后让文字居中.)
<div class="center2">
   <span>222</span>
</div>

.center2 {
  width: 100%;
  margin: 0 auto;
  text-align: center;
}
  1. table-cell 实现几个块级元素一起居中展示.
<div>
   <div class="center3">3111</div>
   <div class="center3">3222</div>
   <div class="center3">3333</div>
</div>

.center3 {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
  width: 200px;
  height: 200px;
  border: 1px solid red;
}
  1. 通过line-height和height,设置元素水平垂直居中.
<div class="center4">
   444
  </div>

.center4 {
  height: 40px;
  line-height: 40px;
  text-align: center;
  background-color: pink;
}
  1. 使用CSS3 translate
    transform: translate(-50%, -50%);
  2. 使用CSS3 calc
    left: calc(50% - 150px);
  3. 使用flex布局 (最好用)
<div class="center5">
   555
  </div>

.center5 {
  display: flex;
  height: 40px;
  align-items: center; // 水平居中
  justify-content: center; // 垂直居中
  background-color: skyblue;
}
举报

相关推荐

0 条评论