<div class="wrap">
<img src="Koala.jpg" alt="梦幻雪冰" title="梦幻雪冰"></div>
效果:欢迎学习交流梦幻雪冰.wrap {
width: 400px;
height: 400px;
background: #fcf;
/*行高等于高度,垂直居中*/
line-height: 400px;
/*水平居中*/
text-align: center;
}
.wrap img {
/* 图片按道理需要设置display:block,在这边条件的限制,所以我们没有设置了 */
/* display: block; */width: 200px;
height: 200px;
/*垂直居中*/
vertical-align: middle;
}
样式:<div class="wrap">
<img src="Koala.jpg" alt="" title="">
<span></span>
</div>
注意:添加了上面为红色部分的代码,添加了span标签,并且设置display属性设置为inline-block来使我们span标签拥有"layout",这样就解决了在IE6不能兼容的问题..wrap {
width: 400px;
height: 400px;
background: #fcf;
/*行高等于高度,垂直居中*/
line-height: 400px;
/*水平居中*/
text-align: center;
}
.wrap img {
/*防止底部出现5px*/
display: inline-block;
width: 200px;
height: 200px;
/*垂直居中*/
vertical-align: middle;
}
.wrap span {
display: inline-block;
}
原理:.wrap {
position: relative;
width: 400px;
height: 400px;
background: #fcf;
}
.box {
position: absolute;
left: 50%;
top: 50%;
width: 200px;
height: 200px;
margin: -100px 0 0 -100px;
background: #999;
}
样式代码:<div class="wrap">
<div class="box">梦幻雪冰</div>
</div>
原理:设置了绝对定位的话,CSS属性top、bottom、left、right都为0的话,这是不可能的,因为.box的元素有设置宽高,所以你只要在设置一个margin:auto,自然就居中了。.wrap {
position: relative;
width: 400px;
height: 400px;
background: #fcf;
}
.box {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
width: 200px;
height: 200px;
margin: auto;
background: #999;
}
<div class="wrap">
<div class="box">
<div class="con">梦幻雪冰</div>
</div>
</div>
缺点:不足之处呢?这种方法只适合现代浏览器,在IE6-7下无法正常运行.wrap {
/*让元素以表格形式渲染*/
display: table;
height: 400px;
width: 400px;
background: #fcf;
}
.box {
/*让元素以表格的单元素格形式渲染*/
display: table-cell;
/*使用元素的垂直对齐*/
vertical-align: middle;
}
.con {
width: 200px;
height: 200px;
margin: 0 auto;
background: #999;
}
<div class="wrap">
<div class="box">
<div class="out">
<div class="con">梦幻雪冰</div>
</div>
</div>
</div>
【第六种方法】利用display:table-cell进行元素水平垂直居中.wrap {
position: relative;
/*让元素以表格形式渲染*/
display: table;
height: 400px;
width: 400px;
background: #fcf;
}
.box {
/*让元素以表格的单元素格形式渲染*/
display: table-cell;
/*使用元素的垂直对齐*/
vertical-align: middle;
/*利用hack技术*/
*position: absolute;
*top: 50%;
*left: 50%;
}
.out {
/*利用hack技术*/
*position:relative;
*top: -50%;
*left: -50%;
}
.con {
width: 200px;
height: 200px;
/*水平垂直居中*/
margin: 0 auto;
background: #999;
}
<div class="wrap">
<div class="box">
梦幻雪冰
</div>
</div>
优点:这种方法的优点和方法三是一样的,不会有高度的限制。.wrap {
display: table-cell;
width: 400px;
height: 400px;
background: #fcf;
vertical-align: middle;
}
.box {
width: 200px;
height: 200px;
margin: 0 auto;
background: #999;
}
联系客服