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

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

水平居中:

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之间的距离,该距离正好等于一行的高度

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

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

相关推荐
2503_928411561 小时前
12.4 axios的二次封装-深拷贝
前端·javascript·vue.js
你真的可爱呀4 小时前
uniapp+vue3项目中的常见报错情况以及解决方法
前端·vue.js·uni-app
差点GDP8 小时前
模拟请求测试 Fake Rest API Test
前端·网络·json
酒尘&9 小时前
Hook学习-上篇
前端·学习·react.js·前端框架·react
houyhea9 小时前
从香港竹脚手架到前端脚手架:那些"借来"的发展智慧与安全警示
前端
哈哈~haha10 小时前
Step 14: Custom CSS and Theme Colors 自定义CSS类
前端·css·ui5
Ndmzi10 小时前
Matlab编程技巧:自定义Simulink菜单(理解补充)
前端·javascript·python
我命由我1234510 小时前
VSCode - VSCode 修改文件树缩进
前端·ide·vscode·前端框架·编辑器·html·js
SoaringHeart11 小时前
Flutter组件封装:验证码倒计时按钮 TimerButton
前端·flutter
San30.11 小时前
深入理解 JavaScript OOP:从一个「就地编辑组件」看清封装、状态与原型链
开发语言·前端·javascript·ecmascript