2025年8种垂直居中的方法

8种垂直居中的方法八种垂直居中的方法 垂直居中的需求经常遇到 通过资料实践了八种垂直居中的方法 以下的方法都围绕着该 HTML 展开 HTML 代码 div class wrap div class box div div CSS

大家好,我是讯享网,很高兴认识大家。

八种垂直居中的方法

垂直居中的需求经常遇到,通过资料实践了八种垂直居中的方法。

 <div class="wrap"> <div class="box"></div> </div> 

讯享网
讯享网.wrap{ width:300px; height:300px; border: 1px solid red; display:flex; justify-content:center; align-items:center; } .box{ height:100px; width:100px boder:1px solid blue; } 

方法2: table-cell

vertical-align 属性设置一个元素的垂直对齐方式。
该属性定义行内元素的基线相对于该元素所在行的基线的垂直对齐。允许指定负长度值和百分比值。这会使元素降低而不是升高。在表单元格中,这个属性会设置单元格框中的单元格内容的对齐方式。

 .wrap{ width: 300px; height: 300px; border: 1px solid red; display: table-cell; text-align: center; vertical-align: middle; } .box{ width: 100px; height: 100px; border: 1px solid blue; display: inline-block; } 

方法3: margin,transform配合


讯享网

讯享网.wrap{ width: 300px; height: 300px; background-color: pink; /* border: 1px solid red; */ /*防止外边距塌陷。解决外边距塌陷的方法: 父元素加overflow:hidden或加上边框*/ overflow: hidden; } .box{ width: 100px; height: 100px; background-color: plum; margin:50% auto; transform: translateY(-50%); } 

方法4: inline-block+vertical-aligin

 .wrap { width: 300px; height: 300px; background-color: pink; text-align: center; line-height: 300px; } .box { width: 100px; height: 100px; /* 重新设置子元素的行高,否则会继承父元素的行高*/ line-height: 100px; background-color: plum; display: inline-block; /* middle 把此元素放置在父元素的中部。 */ vertical-align: middle; } 

方法5:absolute+负margin

讯享网 .wrap{ width: 300px; height: 300px; position: relative; background-color: plum; } .box{ width: 100px; height: 100px; position: absolute; left: 50%; top: 50%; /*宽高的一半*/ margin-left: -50px; margin-top: -50px; background-color: powderblue; } 
 .wrap{ width: 300px; height: 300px; position: relative; background-color: plum; } .box{ width: 100px; height: 100px; position: absolute; left: 0; top: 0; bottom:0; right:0; margin:auto; background-color: powderblue; } 
讯享网 .wrap { width: 300px; height: 300px; position: relative; background-color: plum; } .box { width: 100px; height: 100px; position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); background-color: powderblue; } 
.wrap { width: 300px; height: 300px; display: grid; background-color: plum; } .box { width: 100px; height: 100px; align-self: center; justify-self: center; background-color: powderblue; } 
小讯
上一篇 2025-03-13 17:11
下一篇 2025-03-11 08:13

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/36554.html