元素的水平居中和垂直几种方案

总结一下各种元素的水平居中和垂直居中方案。

水平居中:

1.行内元素水平居中 text-align: center

定义行内内容(例如文字)如何相对它的块父元素对齐;不仅可以让文字水平居中,还可以让行内元素水平居中

注意:给行内元素的父元素设置

  • left:左对齐
  • right:右对齐
  • center:正中间显示
  • justify:两端对齐

2.块级元素的水平居中 margin: 0 auto;

设置当前块级元素(宽度): margin: 0 auto;

原理:一个块级元素默认独占一行,默认宽度是容器的宽度,margin-left,margin-right默认为0,若设置父元素的宽度为100px,本身的宽度是50px,则会自动设置该元素的margin-right为50px,即该元素的整体宽度仍然等于父元素的宽度。

当设置margin-left:auto,margin-right:auto,为了使该元素的宽度等于父容器的宽度,浏览器会使左右两侧的margin会平分剩余的宽度,所以会使该块级元素水平居中。

3.绝对定位

元素有宽度情况下, left0/right0/margin: 0 auto;

4.flex justify-content: center

html 复制代码
display:flex;
justify-content:center;

垂直居中:

1.绝对定位

* 元素有高度情况下, top0/bottom0/margin: auto 0;

html 复制代码
<style>
   .container {
      position: relative;
      height: 300px;
    }
    .box1 {
      position: absolute;
      width: 100px;
      height: 100px;
      top: 0;
      bottom: 0;
      margin: auto 0;
    }
</style>
<div class="container">
    <div class="box1">我居中了</div>
</div>

父元素height:300px,子元素height:100px,margin-top和margin-button会均分垂直方向剩余的距离。

弊端:

1>绝对定位会使元素脱离标准流,可能影响其他元素的布局

2>必须给元素设置高度

2. flex布局(直接使用flex)

html 复制代码
<style>
   .container {
      display: flex;
      align-item:center;
      height: 300px;
    }
    .box1 {
      width: 100px;
    }
</style>
<div class="container">
    <div class="box1">我居中了</div>
</div>

弊端:

1> flex-container中的flex-item都会垂直居中

2> 相对来说, 兼容性差一点点(基本可以忽略)

**3.**相对定位+translate

  • 父元素设置高度,子元素可以不设置高度

  • 先向下移动父元素高度的一半

  • 在向上移动自身高度的一半

top:50%;transform: translate(0,-50%);

html 复制代码
<style>
    .box1 {
      position: relative;
      top:50%;
      transform: translate(0,-50%);
    }
</style>
<div class="container">
    <div class="box1">我居中了</div>
</div>

思考:向下移动父元素高度的一半的时候为什么不适用margin-top:50% ?

margin的百分比是相对于包含块(父元素)的宽度。

4.文本垂直居中

line-height:两行文本base-line之间的距离,该距离正好等于一行的高度

当行高大于字体高度时,剩余的行距会上下均分,所以文字始终位于行高的中间,当设置行高等于容器的高度时,文字正好可以在容器中垂直居中。

注意:该方法只能用于文本,因为文本具有在行高中居中显示的特性

相关推荐
接着奏乐接着舞_9 分钟前
Electron 白屏问题排查及解决记录
前端
htzyl20614 分钟前
前端监控最容易写错的 18 个地方:从平均值到 beforeunload
前端·浏览器
鹿鹿鹿鹿isNotDefined18 分钟前
布局更新后,canvas 重新绘制,出现了只持续一帧的闪烁?!
前端·javascript·vue.js
zhanlang021722 分钟前
HTML 零基础入门到企业实战【第六章 表格标签】6.3 单元格合并:跨行 rowspan、跨列 colspan 实战技巧
前端·html
技术分享官24 分钟前
Geejing WebBuilder 新手指导:用 Wb.Button 按钮组件跑通企业级快速开发平台的前后端闭环
前端·javascript·低代码
SameX24 分钟前
ArkTS 没有 AbortController 怎么取消 setTimeout 链用自增 token 的做法
前端
不可能片场44 分钟前
工程实践 雪花id进JS别当数字传
前端·electron
涛涛ing1 小时前
AI帮我生成了一个炫酷的3D大屏,上线3天就卡崩了
前端
jerrywus1 小时前
用 AMD Radeon Cloud 免费跑 ComfyUI:从开机到打开界面
前端·agent·claude
学以智用1 小时前
CKEditor5 完整详解
前端·后端