大家好,我是翼同学!
目录
1️⃣前言2️⃣背景样式✨背景颜色🪄背景图片🌱背景平铺🔋背景附着🌳背景位置💡复合简写🎐背景透明📌属性总结 3️⃣写在最后1️⃣前言
今天笔记的内容是:
有关CSS背景的样式设置
2️⃣背景样式
通过CSS背景属性,可以为页面元素添加背景样式。
常见的背景样式有背景颜色、背景图片、背景平铺、背景图片位置以及背景固定等内容。
✨背景颜色
一般的,页面元素的颜色默认为透明的(transparent
),我们可以通过background-color
属性可以定义元素的背景颜色。
举个例子:
<!DOCTYPE html><head><style>body {background-color: skyblue;}</style></head><body><h1>滁州西涧</h1><p>独怜幽草涧边生,上有黄鹂深树鸣。</p><p>春潮带雨晚来急,野渡无人舟自横。</p></body></html>
效果如下:
🪄背景图片
background-image属性
描述了元素的背景图像。在实际开发中,会将一些logo之类的图片设置为背景。这种方式的优点在于容易控制图片位置。
语法为:
background-image: url(这里填绝对地址或相对地址指定背景图像);
默认情况下是没有背景图片的。(background-image: none
)
🌱背景平铺
需要注意的是,当我们设置背景图像后,默认情况下背景图片是平铺的。效果如下:
<!DOCTYPE html><head><style>body {background-image: url(images.png);}</style></head><body><h1>Hello World!</h1></body></html>
因此,我们可以通过background-repeat
属性的不同取值来设置图像如何平铺或者不平铺。具体看下表:
下面举例:
<!DOCTYPE html><head><style>body {background-image: url(images.png);background-repeat: no-repeat;}</style></head><body><h1>Hello World!</h1></body></html>
<!DOCTYPE html><head><style>body {background-image: url(images.png);background-repeat: repeat-x;}</style></head><body><h1>Hello World!</h1></body></html>
🔋背景附着
通过background-attachment
属性可以设置背景图像是否固定或者随页面其余部分滚动。(可制作视差滚动效果)
background-attachment
属性有两个取值,具体如下所示:
效果如下所示:
一、无固定
<style>div {background-color: antiquewhite;background-image: url(images.png);background-repeat: no-repeat;background-position: top right;background-attachment: scroll;}</style>
二、有固定
<style>div {background-color: antiquewhite;background-image: url(images.png);background-repeat: no-repeat;background-position: top right;background-attachment: fixed;}</style>
🌳背景位置
通过background-position
属性可以设置图像在背景中的位置。
语法为:
background-position: x y;
需要注意到,这里的x坐标
和y坐标
可以是方位名词也可以是精确单位。具体看下表:
注意点如下:
当指定的x
、y
坐标都是方位名词时,两个值的前后顺序无关,比如top
center
和center
top
的效果一样;当background-position
只有一个取值为方位名词,则默认另一个值为居中对齐;当参数取值为精确单位时,如果只有一个值,则该值一定表示x
的坐标,此时y
坐标默认居中对齐;当background-position
取值是方位名词和精确单位混合使用时,则第一个值表示x
坐标,第二个值表示y
坐标
<!DOCTYPE html><head><style>div {width: auto;height: 800px;background-color: bisque;background-image: url(images.png);background-repeat: no-repeat;background-position: top right;}</style></head><body><div>这里是一段文字</div></html>
效果如下:
💡复合简写
在上述代码中,可以看到背景设置的代码量较多。为了简化背景属性的代码量,我们可以将这些属性合并简写在同一个属性background
中,从而节约代码量。
当使用简写属性background
时,约定顺序如下:
background: 颜色 图片地址 是否平铺 滚动效果 图片位置
这也是开发中提倡的写法。
举个例子:
div {background-color: red;background-image: url(images.png);background-repeat: no-repeat;background-attachment: fixed;background-position: top right;}
上述代码可以简写为:
div {background: red url(images.png) no-repeat fixed top right;}
总结的说,使用简写属性background
时,属性值的顺序为:
background-color
background-image
background-repeat
background-attachment
background-position
备注:属性值不写全,缺失一两项也可以,顺序别换就行。
🎐背景透明
CSS为我们提供背景颜色透明的效果。语法如下:
background: rgba(0, 0, 0, 0.3);
备注:
最后一个参数是alpha透明度
,取值在0
~1
之间,其指定了颜色的不透明度;我们习惯将0.3
的0
省略掉,直接写成:background: rgba(0, 0, 0, .3);
背景透明度是指盒子背景透明,盒子里面的内容并不受影响。
效果举例:
📌属性总结
3️⃣写在最后
好了,本篇笔记就到写这,欢迎大家到评论区一起讨论!