用text-align: center来实现水平居中(只能实现文本的水平居中)css
//html <div class="center"> 文本水平居中 </div> //css .center{width: 200px;height: 100px;background-color: #a036b4; text-align: center; /*水平居中*/ }
2.用margin:auto实现块级元素的水平居中html
<div class="center"> <div class="child_div"></div> </div>
.center{width: 200px;height: 100px;background-color: #a036b4; } .child_div{width: 50px;height: 50px;background-color: blue;margin: 0 auto;/*水平居中*/}
3.使用浮动float来实现水平居中,用float:left;left:50%;同时margin-left:自身宽度的一半;浏览器
<div class="center"> <div class="child_div"></div> </div>
.center{width: 200px;height: 100px;background-color: #a036b4;margin: 0 auto;} .child_div{width:50px;height:50px;background-color:blue; float:left;position:relative;left:50%;margin-left: -25px;/*水平居中*/}
4.固然既然浮动能够实现水平中,那么绝对定位position:absolute也能实现spa
html代码同上,只是修改css中的定位,代码以下
code
.center{width: 200px;height: 100px;background-color: #a036b4;margin: 0 auto;} .child_div{width:50px;height:50px;background-color:blue; position: absolute;left: 50%;margin-left: -25px;/*水平居中*/}
5.用display:inline-block,可是仅inline-block属性是没法让元素水平居中,他的关键之处要在元素的父容器中设置text-align的属性为“center”,这样才能达到效果,并且存在一些问题:须要额外处理inline-block的浏览器兼容性。orm
<div class="center"> <span class="list"></span> </div>
.center{width: 100px;height: 100px;background-color: #a036b4;margin: 0 auto; text-align: center;} .list{display: inline-block; width: 20px; height: 50px; background-color: blue;list-style: none; }
6.用display: table-cell实现水平居中,在父元素中用display: table。htm
7.用<center></center>.it
这三种方法相对前面比较少用,使用相对也复杂些,这里暂不实现操做。。。io
实现垂直居中的几种方法:table
用display: table-cell实现水平居中,在父元素中用display: table,优势内容能够动态改变高度。
<div class="center"> <div class="child_div">content</div> <div class="child_div">content</div> </div>
.center{width: 200px;height: 200px;background-color: #a036b4;display: table; } .child_div{display: table-cell;vertical-align:middle;/*垂直居中*/ width:50px;height:50px;background-color:blue;}
2.用line-height来实现垂直居中,缺点只是在有单个元素时有效。
<div class="child_div">content</div>
.child_div{line-height: 100px;/*垂直居中*/ width:100px;height:100px;background-color:blue;}
3.用绝对定位的方法来实现垂直居中,同水平居中同样,也要去掉自身的高度的一半,具体代码实现以下。
<div class="center"> <div class="child_div">content</div> </div>
.center{width: 200px;height: 200px;background-color: #a036b4; } .child_div{position: absolute;top: 50%;margin-top: -25px;/*垂直居中*/ width:50px;height:50px;background-color:blue;}
4.用margin:auto;实现垂直居中,实现起来比较简单。
<div class="center"> <div class="child_div">content</div> </div>
.center{width: 200px;height: 200px;background-color: #a036b4;} .child_div{position:absolute;top:0;bottom:0; margin:auto;/*垂直居中*/ width:100px;height:100px;background-color:blue;}