如何实现元素⽔平垂直居中?

编程入门 行业动态 更新时间:2024-10-17 11:23:10

<a href=https://www.elefans.com/category/jswz/34/1769177.html style=如何实现元素⽔平垂直居中?"/>

如何实现元素⽔平垂直居中?

居中是⼀个⾮常基础但⼜是⾮常重要的应⽤场景,实现居中的⽅法存在很多,可以将这些⽅法分成 两个⼤类:

  • 居中元素(⼦元素)的宽⾼已知
  • 居中元素宽⾼未知

实现⽅式:

1.利⽤定位+margin:auto

<style>.father{width:500px;height:300px;border:1px solid #0a3b98;position: relative;}.son{width:100px;height:40px;background: #f0a238;position: absolute;top:0;left:0;right:0;bottom:0;margin:auto;}
</style>
<div class="father"><div class="son"></div>
</div>

⽗级设置为相对定位,⼦级绝对定位 ,并且四个定位属性的值都设置了0,那么这时候如果⼦级没 有设置宽⾼,则会被拉开到和⽗级⼀样宽⾼ 这⾥⼦元素设置了宽⾼,所以宽⾼会按照我们的设置来显示,但是实际上⼦级的虚拟占位已经撑满 了整个⽗级,这时候再给它⼀个 margin:auto 它就可以上下左右都居中了 

2.利⽤定位+margin:负值

<style>.father {position: relative;width: 200px;height: 200px;background: skyblue;}.son {position: absolute;top: 50%;left: 50%;margin-left:-50px;margin-top:-50px;width: 100px;height: 100px;background: red;}
</style>
<div class="father"><div class="son"></div>
</div>

 

  • 初始位置为⽅块1的位置
  • 当设置left、top为50%的时候,内部⼦元素为⽅块2的位置
  • 设置margin为负数时,使内部⼦元素到⽅块3的位置,即中间位置

3.利⽤定位+transform 

<style>.father {position: relative;width: 200px;height: 200px;background: skyblue;}.son {position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);width: 100px;height: 100px;background: red;}
</style>
<div class="father"><div class="son"></div>
</div>

translate(-50%, -50%) 将会将元素位移⾃⼰宽度和⾼度的-50% 

这种⽅法其实和最上⾯被否定掉的margin负值⽤法⼀样,可以说是 margin 负值的替代⽅案,并不 需要知道⾃身元素的宽⾼

4.table布局

设置⽗元素为 display:table-cell ,⼦元素设置 display: inline-block 。利⽤ vertical 和 text-align 可以让所有的⾏内块级元素⽔平垂直居中

<style>.father {display: table-cell;width: 200px;height: 200px;background: skyblue;vertical-align: middle;text-align: center;}.son {display: inline-block;width: 100px;height: 100px;background: red;}
</style>
<div class="father"><div class="son"></div>
</div>

5.flex弹性布局

<style>.father {display: flex;justify-content: center;align-items: center;width: 200px;height: 200px;background: skyblue;}.son {width: 100px;height: 100px;background: red;}
</style>
<div class="father"><div class="son"></div>
</div>

css3 中了 flex 布局,可以⾮常简单实现垂直⽔平居中

这⾥可以简单看看 flex 布局的关键属性作⽤:

  • display: flex时,表示该容器内部的元素将按照flex进⾏布局
  • align-items: center表示这些元素将相对于本容器⽔平居中
  • justify-content: center也是同样的道理垂直居中

6.grid⽹格布局 

<style>.father {display: grid;align-items:center;justify-content: center;width: 200px;height: 200px;background: skyblue;}.son {width: 10px;height: 10px;border: 1px solid red}
</style>
<div class="father"><div class="son"></div>
</div>

这⾥看到, gird ⽹格布局和 flex 弹性布局都简单粗暴

小结

上述⽅法中,不知道元素宽⾼⼤⼩仍能实现⽔平垂直居中的⽅法有:

  • 利⽤定位+margin:auto
  • 利⽤定位+transform
  • flex布局
  • grid布局

更多推荐

如何实现元素⽔平垂直居中?

本文发布于:2024-03-11 14:13:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1729160.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何实现   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!