背景相关样式

背景相关样式


css 背景 样式
<div class="box">

</div>

.box{
  width:300px;
  height:300px;
  padding:10px;
  border:10px double red;
/* background-color  设置背景颜色 */
  background-color: #bfa;

/*
  background-image 设置背景图片
  - 可以同时设置背景图片和背景颜色
  - 如果背景图片小于元素 则背景图片会自动在元素中重复平铺将元素铺满
  - 如果背景图片大于元素,将会自动裁剪,会有一部分北京无法显示
  - 一样大则正常显示
  */
  background-image:url("http://img4.imgtn.bdimg.com/it/u=1527486694,2577818700&fm=26&gp=0.jpg");

  /*
  background-repeat 用来设置背景的重复方式
  - repeat 默认值,背景沿着x轴,y轴双方向重复
  - repeat-x 沿x轴方向重复
  - repeat-y 沿y轴方向重复
  - no-repeat 背景图片不重复
  */

  background-repeat: no-repeat;
/*
  background-position 用来设置背景图片的位置
  通过top left right bottom center 来设置背景图片的位置
  使用方位词时必须同时指定两个值,如果只写一个则第二个默认就是center
  也可以通过偏移量来指定背景图片的位置:
    水平方向偏移量 垂直方向偏移量
    background-position: 10px 10px;
  */
  background-position: 50px 50px;
  /*
  background-clip
  可选值:
    border-box 默认值,背景出现在边框的下边
    padding-box 背景不会出现在边框 只出现在内容区和内边距
    content-box 背景只出现在内容区
  */
  background-clip:content-box;
  /*
  background-origin 背景图片的偏移量计算的原点
    padding-box 默认值 background-position从内边距处开始计算
    content-box 背景图片的偏移量从内容区处计算
    border-box 背景图片的偏移量从边框处开始计算
  */
  background-origin: content-box;
  /*
  background-size 设置背景图片的大小
  第一个值表示宽度
  第二个值表示高度
  -如果只写一个 第二个值默认是auto

  cover 图片的比例保持不变 将元素铺满
  contain 图片比例不变 将图片在元素中完整显示
  */
  background-size: contain;
  /*
  background-attachment 背景图片是否跟随元素移动
  - scroll 默认值 背景图片会跟随元素移动
  - fixed 背景会固定在页面中 不会随元素移动
  */
  background-attachment: fixed;
}


--background :背景相关的简写属性,所有背景相关的样式都可以通过其来设置 并且该样式没有顺序要求,也没有哪个属性是必须写的
但是需要注意的是:
	background-size 必须写在 background-position的后面,并且使用/隔开
backgroun-position/background-size

	background-originbackground-clip两个样式,origin要在clip的前面
雪碧图
可以将多个小图片同意放在一个大图片中,通过background-poaition来显示不同的图片,这样图片会同时加载,避免出现闪烁的情况,这种图就称为雪碧图
渐变
通过渐变可以设置一些复杂的背景颜色,可以实现从一个颜色向其他颜色过渡的效果,渐变是图片,需要通过background-image来设置

线性渐变,颜色沿着一条直线发生变化
	linear-gradient()
	linear-gradient(to left,red,yellow)
		线性渐变的开头 可以指定一个渐变的方向
		to left
		to right
		to bottom
		to top
		xxxdeg deg表示度数
		turn 表示圈 0.5turn

		渐变可以同时指定多个颜色 多个颜色默认情况下平均分布
		也可以手动指定渐变的分布情况
		linear-gradient(red 100px,yellow 150px,green 200px)

	radial-gradient() 径向渐变
	默认情况下径向渐变的形状是根据元素的形状来计算的
	-也可以手动指定径向渐变的大小
		circle
		ellipse
		-也可以指定渐变的位置
		-语法:
			radial-gradient(大小 at 位置,颜色 位置,颜色 位置,...)
			大小:
				circle 圆形
				ellipse 椭圆
				closest-side 近边
				closest-corner 近角
				farthest-side 远边
				farthest-corner 远角
			位置:
				top right left center bottom
© 2025 Niko Xie