方法1、利用行高line-height。设置文字的行高与div的高度一样。
<div class="test">毕业在即,自学了一年的前端,竟然不能一下子找到合适的前端实习的工作,允悲。</div>
<style>
div{width:300px;height:50px;}
.test{line-height:50px;text-align:center;}
</style>
方法2、display:table-cell。(不推荐)
.test{display:table-cell;vertical-align:middle;}
方法3、利用css3的transform属性
.test{transform:translate(-50%,-50%);left:50%;top:50%;position:absolute;}
此时,需要给test的父元素设置一个position:relative。
方法4、flex
.test{display:flex;align-items:center;justify-content:center;}
方法5、如果元素的宽高是个定值,那就一点点计算。
方法6、
<div class="parent">
<div class="child"></div>
</div>
<style>
.parent{position:relative;width:300px;height:300px;border:1px solid #ddd;}
.child{position:absolute;width:100px;height:100px;top:0;left:0;bottom:0;right:0;margin:auto;border:1px solid #ddd;}
</style>