水平居中的几种方法(总结)

1.text-align:center(内联或者内联块元素)

适用情况 :父元素是块级元素,子元素是内联或内联块级元素(如文本、图片、inline-block)。

css 复制代码
.parent {
  text-align: center;
}

2.margin: 0 auto (块级元素,需要设定宽度)

适用情况:子元素是块级元素,并且元素有固定宽度。

css 复制代码
.child {
  width: 200px; /* 必须指定宽度 */
  margin: 0 auto;
}

3.flex的justify-content:center(适用于任何元素)

适用情况:适用于任何类型的元素。

css 复制代码
.parent {
  display: flex;
  justify-content: center;
}

4.position:absolute 和 transform (绝对定位元素)

适用情况:子元素是绝对定位元素,父元素需相对定位。

css 复制代码
.parent {
  position: relative;
}

.child {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

5.grid的justify-content:center(适用于任何元素)

适用情况:适用于任何类型的元素。

css 复制代码
.parent {
  display: grid;
  justify-content: center;
}

6.display:table 和margin: 0 auto

适用情况:子元素是块级元素,但父元素的宽度不确定或子元素无明确宽度。

css 复制代码
.parent {
  display: table;
  margin: 0 auto;
}

7.float 和 position:relative

适用情况:需要兼容老旧浏览器。

css 复制代码
.parent {
  position: relative;
}

.child {
  float: left;
  left: 50%;
  position: relative;
  transform: translateX(-50%);
}

8.inline-block和 text-align:center

适用情况:适用于多个块级子元素的水平居中。

css 复制代码
.parent {
  text-align: center;
}

.child {
  display: inline-block;
}

9.inline-flex和justify-content:center

适用情况:用于内联块级元素的水平居中,子元素是行内的 flex 项目。

css 复制代码
.parent {
  display: inline-flex;
  justify-content: center;
}

10.table-cell和text-align:center

适用情况 :在父元素为 table-cell 时,可以通过 text-align 进行居中。

css 复制代码
.parent {
  display: table-cell;
  text-align: center;
}

11.just-self:center(Grid布局)

适用情况:适用于 Grid 布局中的单个网格项目水平居中。

css 复制代码
.parent {
  display: grid;
}

.child {
  justify-self: center;
}

12.text-indent和white-space:nowrap(单文本居中)

适用情况:适用于水平居中文本,尤其是在单行文本的场景下。

css 复制代码
.parent {
  text-align: justify;
  white-space: nowrap;
  text-indent: 50%;
  transform: translateX(-50%);
}
相关推荐
广州灵眸科技有限公司5 小时前
瑞芯微RV1126B开发板(EASY-EAI-PI2) Easy-Eai编译环境准备与更新
服务器·前端·人工智能·python·深度学习
万少6 小时前
我把 Kimi 接进微信,几分钟做了个随手出图助手
前端
xiaofeichaichai6 小时前
网络请求与实时通道
前端·网络
kTR2hD1qb6 小时前
从 Responses API 到 Chat Completions:一个模型网关的设计复盘
linux·前端
kyriewen8 小时前
浏览器缓存最强攻略:强缓存、协商缓存、CDN、更新策略,一篇搞定
前端·面试·浏览器
持敬chijing8 小时前
Web渗透之SQL注入-联合查询注入-注入点数据类型判断
前端·sql·安全·web安全·网络安全·安全威胁分析
LIUAWEIO8 小时前
CSS 让鼠标呈现手型,鼠标悬浮变小手
css·html·css3·html5
卷帘依旧9 小时前
Web3前端一面
前端
古韵9 小时前
告别手写分页逻辑:usePagination 从 50 行到 3 行
java·前端