以前学习垂直居中的时候在网上找了不少方法,看的我眼花撩乱,一直想着整理一下思路,透过那些纷繁的招式看到本质。
首先明确一下概念:面试
理解了以上三点,就基本能看懂各类垂直居中方法了浏览器
这种方法的意思是先把子元素margin和父元素padding的距离置为0,能够理解为子元素和父元素之间没有空隙,而后把margin置为auto,margin平分子元素和父元素之间的距离,也就是说子元素并非真正意义的居中,只是子元素中间的内容居中了,子元素和父元素之间的距离是计算机自动计算的(平分);注意这个方法需配合子元素position:absolute使用,由于默认状况下,margin:auto只对上下起做用,对左右不起做用,加上position使元素脱离标准流,margin:auto可识别布局
<div class="father"> <div class="son"> </div> </div>
.father{ width:400px; height:400px; background-color:pink; position:relative; } .son{ width:100px; height:100px; background-color:red; position:absolute; top:0; bottom:0; left:0; right:0; margin:auto; }
这种方法适用于不知道父元素宽高的状况下(面试官可能会这样问呢)。这种方法是经过先把元素定位到父元素的百分之五十的位置top:50%;left:50%;看下图:学习
注意此时子元素的左上角在父元素中间,整个子元素处于父元素右下四分之一的左上角,而后经过transform:translate(-50%,-50%),使子元素相对自身移动百分之五十,这样子元素就居中啦。须要注意的是自元素中要写定位position:relative;这样才能根据父元素识别到定位的基点。spa
<div class="father"> <div class="son"> </div> </div>
.father{ width:500px; height:500px; background-color:pink; /*position:relative;*/ } .son{ width:100px; height:100px; background-color: red; position:relative; top:50%; left:50%; transform:translate(-50%,-50%); }
两个小栗子讲完了,你明白了么?文章末尾,再送两个小栗子(#^.^#)code
当一个div里没有内容时高度为0,当有内容好比文字时,div就有了高度,难道是文字把div撑开了?其实不是,这个高度是由元素的line-height决定的。当把line-height设置为该div的高度时,div中的文字就居中显示了。代码很简单orm
<div class="line"> qqqqq </div>
.line{ width:100px; height:100px; line-height:100px; text-align:center; background:gray; }
使用table布局也能够实现居中图片
<div class="father"> <div class="son"> qqqqq </div> <div class="son"> qqqqq </div> </div>
.father{ width:400px; height:200px; display:table-cell; text-align:center; vertical-align:middle; //红色框上下居中 background-color:pink; } .son{ width:100px; height:100px; display:inline-block; background-color:red; line-height:100px; //文字在红色框中居中 }