CSS怎么让图片居中

html-css011

CSS怎么让图片居中,第1张

1、首先先在页面里加载一张图片,代码和效果如下图所示:

2、然后设置给图片起一个class名,方便一会儿的操作。

3、然后给图片设置css样式,因为方便的原因就直接在html页面写css样式了。

4、经常使用“margin: 0 auto”来实现水平居中,而一直认为“margin: auto”是不能实现垂直居中,但是实际上,仅需要添加一些限制便能实现效果,就是通过定位:

position: absolute

top: 0

left: 0

bottom: 0

right: 0

设置定位让上下左右都为0,然后通过margin:0 auto,来让元素实现上下左右都居中。

5、设置完CSS样式之后,通过浏览查看代码的效果就可以,可以看到图片已经实现了。

6、最后给大家附上全部的代码:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8" />

<title>使用CSS让图片水平垂直居中</title>

</head>

<body>

<img class="pic" src="img/timg.jpg" alt="" />

</body>

<style type="text/css">

.pic{

margin: auto

position: absolute

top: 0

left: 0

bottom: 0

right: 0

}

</style>

</html>

写个简单的例子给你吧

htlm如下:

<h4>图片水平居中</h4>

<div class="demo1">

<img src="你的图片" alt="">

</div>

<h4>图片垂直居中</h4>

<div class="demo2">

<div class="imgbox">

<img src="你的图片" alt="">

</div>

</div>

<h4>图片水平垂直居中</h4>

<div class="demo3">

<div class="imgbox">

<img src="你的图片" alt="">

</div>

</div>

css如下:

<style type="text/css">

.demo1{width: 200pxheight: 200pxborder: 1px solid #cccdisplay: inline-blocktext-align: center}

.demo1 img{width: 100pxheight: auto}

.demo2{width: 200pxheight: 200pxborder: 1px solid #cccdisplay: table}

.demo2 .imgbox{display: table-cellvertical-align: middle}

.demo2 .imgbox img{width: 100pxheight: auto}

.demo3{width: 200pxheight: 200pxborder: 1px solid #cccdisplay: table}

.demo3 .imgbox{display: table-cellvertical-align: middletext-align: center}

.demo3 .imgbox img{width: 100pxheight: auto}

</style>