css怎么做才能只显示图片的一部分

html-css020

css怎么做才能只显示图片的一部分,第1张

CSS Sprite

需要知道大图的网地,小图标在图上的位置偏移(写进css里的background-position要加负号),和大小。

<style>

.icon {

  background:url(background.png)

  background-repeat:no-repeat

  background-position:-25px -374px

  height:16px

  width:24px

}

</style>

<div class=".icon"></div>

用background-position: 给背景定位

.img{ background-image:url(bj.jpg)width:79px height:30background-position: 00}显示绿色背景

.img{ background-image:url(bj.jpg)width:79px height:30background-position: 0 30}显示黄色背景

下面这样做应该可以吧

-------------------------------————————————————————————

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=gb2312">

<title>无标题文档</title>

<style type="text/css">

<!--

body,td,th {

font-size: 12px

}

.img{ background-image:url(bj.jpg)width:79px height:30}

.01{background-position: 0 0}

.02{background-position: 0 30}

-->

</style></head>

<body>

<div class="img 01"></div>

<div class="img 02"></div>

</body>

</html>

可以使用以下几种方式:

1、相对定位方式,设置图片的position属性为relative,然后设置left top属性为负数,做到显示中间区域,外层标签要设置overflow属性为hidden不然会撑大。

2、把图片当做背景使用,然后设置背景居中或者手工填写位置。

3、使用图片margin属性,外层标签要设置overflow属性为hidden不然会撑大。

代码如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>

<head>

    <title>图片</title>

<style>

.div1{

    width:300px

    height:400px

    border:1px solid #4EC83B

    overflow: hidden

}

.div1 img {

    position: relative

    left: -100px

    top: -150px

}

</style>

</head>

<body>

<div style="float:leftmargin:10px">

    第一种

    <div class="div1">

        <img src="img1.jpg" width="500" height="700" alt="" />

    </div>

</div>

<div style="float:leftmargin:10px">

    第二种

    <div style="width:300pxheight:400pxbackground-image:url(img1.jpg)background-repeat: no-repeatbackground-position:center centerborder:1px solid #4EC83B">

    </div>

</div>

<div style="float:leftmargin:10px">

    第三种

    <div style="width:300pxheight:400pxborder:1px solid #4EC83B overflow: hidden">

        <img src="img1.jpg" width="500" height="700" style="margin:-150px -100px" />

    </div>

</div>

</body>

</html>

效果如下: