文字单行居中,多行居左实现

文字单行居中,多行居左实现


css 布局 前端
<div class="outer">
  <div class="ib">
    <p>文字文字文字</p>
  </div>
  <div class="ib">
    <p>文字文字文字文字文字文字文字文字文字</p>
  </div>
  <hr />
  <div class="tb">
    <p>文字文字文字</p>
  </div>
  <div class="tb">
    <p>文字文字文字文字文字文字文字文字文字</p>
  </div>
  <hr />
  <p class="prt">文字文字文字</p>
  <p class="prt">文字文字文字文字文字文字文字文字文字</p>
  <hr />
  <p class="flex">文字文字文字</p>
  <p class="flex">文字文字文字文字文字文字文字文字文字</p>
  <hr />
  <p class="fit">文字文字文字</p>
  <p class="fit">文字文字文字文字文字文字文字文字文字</p>
  <hr />
  <div class="ft">
    <p>文字文字文字</p>
  </div>
  <div class="ft">
    <p>文字文字文字文字文字文字文字文字文字</p>
  </div>
  <hr />
</div>
p {
  margin: 4px;
}
.outer {
  width: 200px;
  height: 600px;
  border: 1px solid;
  margin: 20px auto;
  padding: 0 10px;
}
// 方法一:inline-block
.ib {
  text-align: center;
}
.ib > p {
  display: inline-block;
  text-align: left;
}

// 方法二:table display:table 或者直接使用table标签,效果一样,就不重复写了
.tb {
  display: table;
  margin: 0 auto;
  text-align: left;
}

// 方法三 position:relative+transform
.prt {
  display: inline-block;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
}

// 方法四 flex
.flex {
  display: flex;
  justify-content: center;
}

// 方法五 width:fit-content+margin:auto
// width:fit-content可以实现元素收缩效果的同时,保持原本的block水平状态,于是,就可以直接使用margin:auto实现元素向内自适应同时的居中效果了。相比方法一可以少一层标签
.fit {
  width: fit-content;
  width: -moz-fit-content; //火狐需要-moz-前缀
  margin: 0 auto;
}

// 方法六 flaot+transform 跟方法三类似, 但是要加一层标签
.ft {
  position: relative;
  float: left;
  left: 50%; /**父级设置50%**/
}
.ft > p {
  position: relative;
  float: left;
  left: -50%; /**子级设置-50%**/
}

这边提供了在线展示的链接

codepen

© 2025 Niko Xie