css的图片居中

html-css05

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>

css中有一个background-position 属性设置背景图像的起始位置。

他有以下可能的值:

1,top left  左上角

2,top center  正上方

3,top right  右上方

4,center left  正左方

5,center center  正中

6,center right   正右方

7,bottom left  左下方

8,bottom center  正下方

9,bottom right   右下方

所以要是背景图居中显示,css里边加上下边这条属性:

background-position:center center

css使整个页面背景图片居中,你是可以给一个总的div设置好一定的width和height,然后给它来设置背景图片,在通过margin让他们居中,同时,background的repeat来平铺实现,具体代码:

<html>

<head>

<style>

#div1{

width:960px

height:1200px

border:1px soild #f00

background:url('图片地址')repeat 0px 0px

margin:0 auto

}

</style>

</head>

<body>

<div id='div1'>

</div>

</body>

</html>