css水平垂直居中方式?
一、设置margin:auto;
1 <div class="external"> 2 <div class="inside"></div> 3 </div>
使用 margin: auto; 元素仅会水平居中,并不会进行垂直居中。此时需要设置元素的 position 为 absolute,父级元素的 position 为 relative,同时元素的上下左右都需要设置为 0。
1 .external { 2 position: relative; 3 width: 400px; 4 height: 60px; 5 background: #fff; 6 } 7 .inside { 8 position: absolute; 9 top: 0; 10 right: 0; 11 bottom: 0; 12 left: 0; 13 width: 40px; 14 height: 20px; 15 margin: auto; 16 background: red; 17 }
二、弹性布局:display: flex;
1 .external { 2 display: flex; 3 justify-content: center; 4 align-items: center; 5 width: 400px; 6 height: 60px; 7 background: #fff; 8 } 9 .inside { 10 width: 40px; 11 height: 20px; 12 background: red; 13 }
三、设置position: absolute;
1 .external { 2 position: relative; 3 width: 400px; 4 height: 60px; 5 background: #fff; 6 }
当知道元素宽度和高度时,可以设置margin-top和margin-left为负的宽高的一半。
1 inside { 2 position: absolute; 3 top: 50%; 4 left: 50%; 5 width: 40px; 6 height: 20px; 7 margin-top: -10px; 8 margin-left: -20px; 9 background: red; 10 }
当知道元素宽度和高度时,也可以利用calc
计算设置top
和left。
1 .inside { 2 position: absolute; 3 top: calc(50% - 10px); 4 left: calc(50% - 20px); 5 width: 40px; 6 height: 20px; 7 background: red; 8 }
当未知元素宽度和高度时,可以设置position: absolute
和transform: translate(-50%, -50%)。
1 .inside { 2 position: absolute; 3 top: 50%; 4 left: 50%; 5 width: 40px; 6 height: 20px; 7 background: red; 8 transform: translate(-50%, -50%) 9 }
四、设置水平对齐和行高
通过设置text-align
和 line-height
实现单行文本水平垂直居中。
1 <div class="external"> 2 <div class="inside">水平居中</div> 3 </div>
1 .external { 2 width: 400px; 3 height: 60px; 4 background: #fff; 5 } 6 .inside { 7 line-height: 60px; 8 text-align: center; 9 }
五、设置grid(兼容性不太好,不推荐)
1 <div class="external"> 2 <div class="inside">水平居中</div> 3 </div>
设置justify-self
、align-self
或者margin: auto
1 .external { 2 display: grid; 3 width: 400px; 4 height: 60px; 5 background: #fff; 6 } 7 .inside { 8 justify-self: center; 9 align-self: center; 10 // margin: auto; 11 }
设置justify-items
、align-items
或justify-content
、align-content
1 .external { 2 display: grid; 3 justify-content: center; 4 align-items: center; 5 width: 400px; 6 height: 60px; 7 background: #fff; 8 }
六、设置table-cell
1 .external { 2 display: table-cell; 3 text-align: center; 4 vertical-align: middle; 5 width: 400px; 6 height: 60px; 7 background: #fff; 8 } 9 .inside { 10 display: inline-block; 11 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现