CSS背景background八种属性

想必大家对背景不陌生,让我为大家介绍一下吧!

属性名 简述
background-color 背景颜色
background-image 背景图片
background-position 背景定位
background-size 背景大小
background-repeat 背景是否平铺
background-attachment 背景是否随滚动条固定
background-clip 背景图片裁剪区域
background-origin 背景图片的位置区域
background 复合属性

我们给元素添加背景相关样式之前,必须要有宽度和高度,宽度可以省略,会继承父级的宽度,如果在没宽高的元素上使用则无效

一、背景颜色

我们可以给背景添加颜色,我们该如何实现呢?
颜色我们可以使用英文颜色,或者rgba,或者十六进制
接下来让我为大家展示一下

div {
	width: 200px;
	height: 200px;
	/* 第一种英语颜色 */
	background-color: black;
	/* 第二种rgba */
	/* background-color: rgba(0, 0, 0, 1); */
	/* 第三种十六进制 */
	/* background-color: #000; */
}

展示效果:
CSS背景background八种属性_第1张图片

二、背景图片

background-image属性描述了元素的背景图像
语法:background-image : none | url(url)

div {
	width: 1200px;
	height: 300px;
	 /* 千万别落下url */
	background-image: url(./1.jpg);
}

三、背景大小

设置背景的尺寸
语法:
1.用长度值指定背景图片大小,不允许负值
2.用百分比指定背景图片大小,不允许负值
3.auto : 背景图片的真实大小 (默认值)
4.contain : 将背景图片等比缩放,直到完全覆盖容器,图片会尽可能全的显示在元素上,但要注意:背景图片包含在容器内,但要注意:可能会造成容器里部分区域没有背景图片。
5.cover : 将背景图片等比缩放,直到完全覆盖容器,图片会尽可能全的显示在元素上,但要注意:背景图片有可能显示不完整。

四、背景平铺

大家看下图,背景平铺了所以我们要使用到background-repeat
语法:background-repeat : repeat | no-repeat | repeat-x | repeat-y
背景平铺时:

div {
	width: 1200px;
	height: 300px;
	/* 千万别落下url */
	background-image: url(./1.jpg);
	/* 设置背景不平铺 */
	background-repeat: no-repeat;
}

背景不平铺时:
CSS背景background八种属性_第2张图片

五、背景定位

利用background-position属性可以改变图片在背景中的位置
语法:background-position : x y ;
参数代表的意思:x坐标和y坐标。可以使用方位名词 或者 精确单位

参数值 说明
length 百分比 由浮点数字和单位标识符组成的长度值
position top center bottom left center right 方位名词
        div {
            width: 1200px;
            height: 500px;
            background-color: pink;
            /* 千万别落下url */
            background-image: url(./1.jpg);
            /* 设置背景不平铺 */
            background-repeat: no-repeat;
            /* 背景位置 */
            background-position: center left;/* 可以和其他方位组合使用 */
        }

CSS背景background八种属性_第3张图片
精确单位
使用px,可以自己动手试试

六、背景是否随滚动条固定

设置背景图像是否固定或者随着页面的其余部分滚动
语法:background-attachment : fixed;
滑动滚动条背景图片被固定住了

七、背景图片裁剪区域

设置背景图的向外裁剪区域
background-clip
语法:
1.padding-box : 从padding区域开始向外裁剪背景。
2.border-box : 从border区域开始向外裁剪背景(默认值)
3.content-box : 从content 区域开始向外裁剪背景
4.text : 背景图只呈现在文字上
注意:若值为text , 那么background-clip要加上-webkit-

八、背景图片的位置区域

设置背景图的原点
background-origin
语法:
1.padding-box : 从padding区域开始显示背景图像。(默认值)
2.border-box : 从border区域开始显示背景图像。
3.content-box : 从content 区域开始显示背景图像

九、复合属性

语法:background : [background-color]背景颜色 | [background-image] 背景图片|
[background-position]背景定位[/background-size]背景大小 | [background-repeat] 背景是否平铺|[background-attachment]背景是否随滚动条固定
| [background-clip] 背景图片裁剪区域| [background-origin]背景图片的位置区域

感谢大家的阅读,本人文笔有限,如有不对的地方,可以向我提出,感谢大家!

你可能感兴趣的:(css,前端)