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>

可以为盒子添加“text-align: center”样式使图片在盒子中居中。

1、新建html文档,在body标签中添加一个div盒子,然后在这个div盒子中添加一张图片:

2、为div盒子和图片添加一些样式,这时默认情况下图片会向盒子的左上角对齐:

3、为div盒子添加“text-align: center”样式,这时图片会在div盒子中居中对齐: