background-position 个人理解

时间:2023-03-09 17:54:41
background-position 个人理解

background-position
这里先说像素  百分比比较复杂
background-position:xxpx xxpx  这里第一个值指的是x轴坐标  第二个值是y轴坐标
这里使用的坐标系和数学中的坐标系不同   它大概是这样的
----------------->  x轴
|
|
|
|
|
|
|
|
V
y轴

先说说图片比div小得情况 http://www.w3schools.com/cssref/playit.asp?filename=playcss_background-position
此时移动的是图片
再说说几个特殊的值  x轴 left right center y轴 top bottom center
left和top相当于0px right和bottom相当于使图像到达边界的最大值 center就是使图像来到中间位置的值
所以可以用center center来使图片居中

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<style type="text/css">
.one{
width: 500px;
height: 800px;
border: 1px solid black;
background-image: url(http://s1.meituan.net/www/css/i/sp-header-new.vefe0f047.png);
background-repeat: no-repeat;
background-position: right bottom;/*使图片停靠在div的右下区域*/
background-position: center center;/*图片在div的中间位置*/
background-position: center top;/*横轴上 图片居中 纵轴上 图片靠顶*/
background-position: 30px 50px;
} .two{
width: 43px;
height: 40px;
border: 1px solid black;
background-image: url(http://s1.meituan.net/www/css/i/sp-header-new.vefe0f047.png);
background-position: right bottom;/*和前面的规则一样 还是停留在右下区域 确切的说 使得图像的右下角 对齐于div的右下角*/
/*另外一种理解的方式 先假设div区域很大 根据one里面那样对齐好图片之后 因为是停靠在右下区域
抓住div的右下角不动 缩小div*/
/*最好的理解方式是 尤其是对于div小于原始图片很多的时候 这里我们移动的是div 对于right bottom
就是将div相对图片来说 移动到图片的右下角的位置*/
background-position: center center;/*将div移动到相对于图片的中心位置*/
background-position: center top;/*将div移动到相对于图片的x轴中间 y轴的顶部*/
background-position: -43px -150px;
/*根据书上的解释 我们说是图片左上角 相对于div左上角在x轴反向移动43px y轴反向移动150px*/
/*或者使用我的理解方式 div相对于图片 x轴移动43px y轴移动150px*/ }
</style>
<body>
当图片比div小的时候 这个x轴 y轴的数值表示的是图片左上角距离div左上角的距离
<div class='one'></div>
当图片比div大的时候 可以通过x轴 y轴设置负值来实现对图片的裁剪
实际上就是控制图片位置 显示只需要显示的部分
<div class='two'></div>
</body>
</html>