css怎样实现图片水平垂直居中

小编给大家分享一下css怎样实现图片水平垂直居中,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

1、text-align: center实现图片水平居中

text-align一般用于文本的水平居中,也可以用于图片,代码如下:

CSS部分:

<style type="text/css">
    div{
        text-align: center;
        width: 500px; 
        border: green solid 1px;
        }
</style>

HTML部分:

<div>
    <img src="img/logo.png" />
</div>

2、line-height和text-align: center 实现图片的水平垂直居中

设置line-height的值等于height,可以实现垂直居中,text-align: center可以实现水平居中。HTML部分一样,CSS代码如下:

<style type="text/css">
div{
text-align: center; 
width: 400px;
height:200px; 
line-height:200px; 
border: green solid 1px;
}
img{
vertical-align: middle;
}
</style>

3、display: table和display: table-cell实现图片水平垂直居中

利用table方法设置display: table,display: table-cell,但是这种方法并不兼容IE6/IE7,如果你不需要支持IE67可以使用这种方法

css样式直接写在标签里面,代码如下:

<div style="text-align: center; width: 400px;height:200px; display: table;border: green solid 1px;">
    <span style="display: table-cell; vertical-align: middle; ">
        <img src="img/logo.png"  />
    </span>
</div>

4、position实现图片水平垂直居中

定位方法:在父盒子中设置相对定位,在子盒子中设置绝对定位,即所谓的父相对子绝对。设置图片位置左边为50%,上边为50%,(注意:这样并没有垂直居中),还需要设置margin-left为图片长度的一半,margin-top为图片高度的一半。HTML部分一样,CSS代码如下;

<style type="text/css">
div{
width: 400px;
height:200px; 
position: relative;
border: green solid 1px;
}
img{
width: 200px;
height: 50px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -25px;
}
</style>

5、背景background实现图片水平垂直居中

利用background: url no-repeat center center 实现图片的水平垂直居中

div{
width: 400px;
height:200px; 
border: green solid 1px;
background: url(img/logo.png) no-repeat center center ;
}

以上是“css怎样实现图片水平垂直居中”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!