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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了