方法一:使用position 元素已知宽度
<div class="box"> ???<div class="content"></div></div><style> ???.box{width:400px; height: 400px;background:red;position: relative;} ???.content{width:150px;height: 100px;background:green; position: absolute;top:200px;left: 200px;margin-left:-75px;margin-top: -50px;}</style>
方法二:position tranform 元素宽度未知
<div class="box"> ???<div class="content"></div></div><style> ???.box{width:400px; height: 400px;background:red;position: relative;} ???.content{width:150px;height: 100px;background:green; position: absolute;top:200px;left: 200px;transform: translate(-50%,-50%);}</style>
得到的效果和上图一样
当使用这种方法将文字放在div水平垂直的位置的时候,会出现字体边缘模糊的结果,解决方法是:使用flex完成垂直居中,设置排列方向为column,并设置justify-content: center,最后用text-align: center完成水平居中。方能保证文字显示清晰。
方法三:felx布局
<style> ???.box{width:400px; height: 400px;background:red;display: flex;justify-content: center;align-items: center;} ???.content{width:150px;height: 100px;background:green;}</style><div class="box"> ???<div class="content"></div></div>
效果和上图一样
方法四:table-cell布局
因为table-cell相当与表格的td,td为行内元素,无法设置宽和高,所以嵌套一层,嵌套一层必须设置display: inline-block;td的背景覆盖了红色,不推荐使用
<style> ???.box{width:400px; height: 400px;background:red;display: table;} ???.content{background:blue;display: table-cell;vertical-align: middle;text-align:center;} ???.inner{background:green;display: inline-block;width: 150px;height: 100px;}</style><div class="box"> ???<div class="content"> ???<div class="inner"></div> ???</div></div>
css实现水平垂直居中方法总结
原文地址:https://www.cnblogs.com/mexiaoxia/p/9839361.html