div+css 背景图片的定位取图方法

CSS中背景图片定位方法
 关键字: css中背景图片定位方法
 在CSS中,背景图片的定位方位有3种:
 
1)关键字:background-position: top right;
2)像素:background-position: 0px 0px;
3)百分比:background-position: 0% 0%;
 

上面这三句语句,都将图片定位在背景的左上角,表面上看效果是一样的,实际上第三种定位机制与前两种完全不同。
 前两种定位,都是将背景图片左上角的原点,放置在规定的位置。请看下面这张图,规定的位置是“20px 10px”和"60px 50px",都是图片的原点在那个位置上,图中用X表示。
 
      但是第三种定位,也就是百分比定位,不是这样。它的放置规则是,图片本身(x%,y%)的那个点,与背景区域的(x%,y%)的那个点重合。比如,如果放置位置是“20% 10%”,实际结果如下图,可以看到这个点是在图片本身的“20% 10%”的位置上。
 

下面是一个有趣的例子。
 背景图片是四个边长为100px的方块叠在一起:请问怎样才能将其横过来? 答案是,在网页中先设置四个div区域:
 
<div class="box1">
 </div>
 <div class="box2"">
 </div>
 <div class="box3">
 </div>
 <div class="box4">
 </div>
 
然后,这样编写CSS:
 
.box1, .box2, .box3, .box4 {
 float:left;
 100px;
 height:100px;
 position:relative;
 background: #F3F2E2 url(1234.png) no-repeat;
 }
 .box1 {
 background-position:0% 0%;
 }
 .box2 {
 background-position:0% 33.33333%;
 }
 .box3 {
 background-position:0% 66.66666%;
 }
 .box4 {
 background-position:0% 100%;
 }可以看到第二和第三个方块的设置,并不是一般想象中的“0% 25%”和“0% 75%”。
 不过说实话,这个例子用像素设置法更容易一些。使用百分比设置的主要优势在于,当页面缩放的时候,背景图片也会跟着一起缩放。

/*盒子的css样式*/
 #box{ 500px; height:180px; border:1px #ccc solid;}
 /*全部重复背景*/
 .repeat{ background:url(bg.gif);}
 /*水平方向重复*/
 .repeatx{ background:url(bg.gif) repeat-x;}
 /*垂直方向重复*/
 .repeaty{ background:url(bg.gif) repeat-y;}
 /*背景不重复*/
 .norepeat{ background:url(bg.gif) no-repeat;}
 /*背景左侧中间对齐*/
 .left{ background:url(bg.gif) no-repeat left center;}
 /*背景右侧中间对齐*/
 .right{ background:url(bg.gif) no-repeat right center;}
 /*图片背景水平方向和垂直方向都居中*/
 .center{ background:url(bg.gif) no-repeat center center;}
 /*圆心是左侧上部的 那个点 距离水平方向50px 垂直方向20px*/
 .dingwei{ background:url(bg.gif) no-repeat 50px 20px;}

原文地址:https://www.cnblogs.com/ae6623/p/4416527.html