css居中(自己常用的)

水平居中:

1.text-aligin:center  

如果仅使用 text-aligin:center   是无法达到水平居中的效果的,为什么?

text-aligin:center  需要在行内块元素上使用的,而盒子是块级元素,所以,需要将盒子转换为行内块元素 text-aligin:center  才能生效。

<div style="text-align: center;">

  <div style="display: inline-block;"></div>

</div>

2. display:flex

<div style="display: flex;justify-content: center;">

  <div></div>

</div>

3.position(子元素绝对定位,父元素相对定位)  ,由于子元素有width属性,所以left:50%会导致子元素往右偏,因此需要往左 半个子元素 的宽度 

<div style="position: relative;">

  <div style="position: absolute; left: 50%; margin-left: -100px;"></div>  

</div>

4.margin-auto

<div style="overflow: hidden">

  <div style="margin: auto;"></div>  

</div>

 参考https://blog.csdn.net/qq_53985958/article/details/125510763

 

垂直居中:

1.table-cell

<div style="display: table-cell;vertical-align: middle;">

  <div></div>

</div>

2.display:flex

<div style="display: flex;align-items:Center;">

  <div></div>

</div>

3. position 子绝对 父相对(与上面一样,要负子元素宽度的一半)

<div style="position:relative;">

  <div style="position: absolute;margin-top:-25px;top:50%"></div>

</div>

参考https://m.php.cn/faq/473645.html

posted @   妞妞猪  阅读(50)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示