如何让一个行内元素(如image)在div中居中
1、第一种:用vertical-align#
vertical-align:middle 是依赖div内子元素最高的行高来实现对某元素居中的,而我们只需要建立一个新元素,给他加上inline-block
属性 再把他高度设置为100%就行了,在下面的<img>设置vertical-align就生效了
<div class="method1"> <span class="tiptop"></span> <img class="test" src="img/Dota2.jpg" alt="dota2"> </div> <style> .method1{ text-align:center; } .tiptop{ height:100%; display:inline-block; vertical-align:middle; } img{ vertical-align:middle; } </style>
2、第二种:flex布局(注意浏览器兼容性)#
<div class="method2"> <img src="img_p1_title.png"> </div> <style> .method2 { display: flex; justify-content: center; //弹性盒子对象在主轴上的对齐方式 align-items: center; //定义flex子项在flex容器的当前行的侧轴(纵轴)方向上的对齐方式。 background-color:#00a0e9; height:200px; } .method2 img { width:20px; height:30px; background-color:#0A58A0; } </style>
3、绝对定位的方式#
<div class="method3"> <span>第三种方法</span> </div> <style> .method3 { width:100%; height: 200px; font-size: 18px; position: relative; background-color:#00a2d4; } .method3 span { width:100px; height:100px; background-color:#00ACED; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } </style>
4、使用display:table-cell配合vertical-align:center(淘宝也是这样用的)#
<div class="method4"> <span>第四种方法</span> </div> <style> .method4 { width: 200px; height: 200px; vertical-align: middle; display: table-cell; /*只支持IE8+及现代浏览器,与position:absolute;或float:left;属性尽量不一起用*/ text-align: center; background-color:#00ACED; } .method4{ width:100px; height:100px; background-color:#0A58A0; } </style>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?