css实现水平垂直居中的几种方式总结

css实现水平垂直居中的几种方式总结

首先是html部分的代码:

<div style="width:300px;height:300px;border:1px solid;" class = "wrap">

    <div style="width:100px; height:100px;border:1px solid" class=box></div>

</div>


第一种方式: 弹性盒子

.wrap{

display: flex;

justify-content: center;

align-item: center;

}

种方式: 借助table-cell

.wrap{

display: table-cell;

text-align: center;

vertifcal-align: middle;

}

.box{

display: inline-block;

}



第三种: margin+transform实现

.wrap{

overflow: hidden;

}

.box{

margin: 50% auto;

transform : translateY(-50%);

}


第四种: inline-block + vertival-align

.wrap{

text-align: center;

line-height: 300px;

}

.box{

display: inline-block;

vertical-align: middle;

}


第五种: absolute + margin

.wrap{

position: relative;

}

.box{

position: absolut;

left: 50%;

top: 50%;

margin-left: -50px;

margin-top: -5opx;

}


第六种: absolut + margin:auto

.wrap{

position: relative;

}

.box{

position: absolute;

left: 0;

top:0;

right: 0;

bottom: 0;

margin: auto;

}

第七种: absolute + transform

.wrap{

position: relative;

}

.box{

position: absolute;

left: 50%;

top: 50%;

transform: translate(-50%, -50%);

}


第八种: grid

.wrap{

display: grid;

}

.box{

align-self: center;

justify-self: center;

}

 上面的方式应该看具体的要求来运用, 没有什么硬限的要求

文章目录

css实现水平垂直居中的几种方式总结

第一种方式: 弹性盒子flex

第二种方式: 借助table-cell

第三种: margin+transform实现

第四种: inline-block + vertival-align

第五种: absolute + margin

第六种: absolute + margin:auto

第七种: absolute + transform

第八种: grid

————————————————

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容