欢迎来到DIVCSS5查找CSS资料与学习DIV CSS布局技术!
  1、text-align:center实现图片水平居中
 
  text-align一般用于文本的水平居中,也可以用于图片,代码如下:
 
  CSS部分:
 
  <styletype="text/css">
 
  div{
 
  text-align:center;
 
  width:500px;
 
  border:greensolid1px;
 
  }
 
  </style>
 
  HTML部分:
 
  <div>
 
  <imgsrc="img/logo.png"/>
 
  </div>
 
  效果图:
 
  图片垂直居中1.jpg
 
  2、line-height和text-align:center实现图片的水平垂直居中
 
  设置line-height的值等于height,可以实现垂直居中,text-align:center可以实现水平居中。HTML部分一样,CSS代码如下:
 
  <styletype="text/css">
 
  div{
 
  text-align:center;
 
  width:400px;
 
  height:200px;
 
  line-height:200px;
 
  border:greensolid1px;
 
  }
 
  img{
 
  vertical-align:middle;
 
  }
 
  </style>
 
  效果图:
 
  图片垂直居中3.jpg
 
  3、display:table和display:table-cell实现图片水平垂直居中
 
  利用table方法设置display:table,display:table-cell,但是这种方法并不兼容IE6/IE7,如果你不需要支持IE67可以使用这种方法
 
  css样式直接写在标签里面,代码如下:
 
  <divstyle="text-align:center;width:400px;height:200px;display:table;border:greensolid1px;">
 
  <spanstyle="display:table-cell;vertical-align:middle;">
 
  <imgsrc="img/logo.png"/>
 
  </span>
 
  </div>
 
  4、position实现图片水平垂直居中
 
  定位方法:在父盒子中设置相对定位,在子盒子中设置绝对定位,即所谓的父相对子绝对。设置图片位置左边为50%,上边为50%,(注意:这样并没有垂直居中),还需要设置margin-left为图片长度的一半,margin-top为图片高度的一半。HTML部分一样,CSS代码如下;
 
  
 
  <styletype="text/css">
 
  div{
 
  width:400px;
 
  height:200px;
 
  position:relative;
 
  border:greensolid1px;
 
  }
 
  img{
 
  width:200px;
 
  height:50px;
 
  position:absolute;
 
  left:50%;
 
  top:50%;
 
  margin-left:-100px;
 
  margin-top:-25px;
 
  }
 
  </style>
 
  5、背景background实现图片水平垂直居中
 
  利用background:urlno-repeatcentercenter实现图片的水平垂直居中
 
  div{
 
  width:400px;
 
  height:200px;
 
  border:greensolid1px;
 
  background:url(img/logo.png)no-repeatcentercenter;
 
  }
 
  总结:以上介绍了图片居中的5种方法,各不相同,具体用什么方法,看个人习惯和工作需要,初学者可以自己动手尝试,希望可以帮助到你!






本文转载自中文网

 

如需转载,请注明文章出处和来源网址:http://www.divcss5.com/css3-style/c55307.shtml