0
点赞
收藏
分享

微信扫一扫

CSS篇十——(3)

一、CSS的背景

CSS设置背景颜色、背景图片、背景平铺、背景图片位置见​​CSS篇十——(2)​​

5. 背景图像固定(背景附着)

background-attachment属性设置背景图像是否固定或者随着页面的其余部分滚动 。

使用场景:background-attachment后期可以制作视差滚动的效果。

5.1 使用方式

background-attachment: scroll | fixed

参数

作用

scroll

背景图像是随对象内容滚动

fixed

背景图像固定

代码示例:

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS背景之背景固定</title>
<style>
body {
background-image: url(images/wangzhe.png);
background-repeat: no-repeat;
background-position: center top;
/* 把背景图片固定住 */
background-attachment: fixed;
color: steelblue;
font-size: 20px;
}
</style>
</head>

<body>
<p>天王盖地虎,宝塔镇河妖</p>
<p>天王盖地虎,宝塔镇河妖</p>
<p>天王盖地虎,宝塔镇河妖</p>
<p>天王盖地虎,宝塔镇河妖</p>
<p>天王盖地虎,宝塔镇河妖</p>
</body>

</html>

CSS篇十——(3)_html

6. 背景属性复合写法

为了简化背景属性的代码,可以将这些属性合并简写在同一个属性background中。从而节约代码量。

6.1 使用方式

当使用简写属性时,内有特定的书写顺序,一般习惯约定顺序为:

background: 背景颜色 背景图片地址 背景平铺 背景图像滚动 背景图片位置;

background: transparent url(image.jpg) repeat-y fixed top;

实际开发中,更提倡复合性写法

代码示例:

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
/* background-image: url(images/wangzhe.png);
background-repeat: no-repeat;
background-position: center top;
/* 把背景图片固定住 */
/* background-attachment: fixed;
background-color: black; */
background: black url(images/wangzhe.png) no-repeat fixed top center;
color: steelblue;
font-size: 20px;
}
</style>
</head>

<body>
<p>天王盖地虎,宝塔镇河妖</p>
<p>天王盖地虎,宝塔镇河妖</p>
<p>天王盖地虎,宝塔镇河妖</p>
<p>天王盖地虎,宝塔镇河妖</p>
<p>天王盖地虎,宝塔镇河妖</p>
<p>天王盖地虎,宝塔镇河妖</p>
<p>天王盖地虎,宝塔镇河妖</p>
</body>

</html>

CSS篇十——(3)_背景图片_02

7. 背景色半透明

CSS3提供了背景色半透明的效果。

7.1 使用方式

background: rgba(0,0,0,0.3);

  • 最后一个参数是alpha透明度,取值范围在0~1之间
  • 习惯把0.3的0省掉,写为background: rgba(0,0,0, .3);
  • 注意:背景半透明是指盒子背景半透明,盒子里面的内容不受影响
  • CSS3新增属性,是IE9+版本浏览器才支持的
  • 在实际开发中不太关注兼容性写法,可以放心使用

代码示例:

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS背景之背景颜色半透明</title>
<style>
div {
width: 500px;
height: 300px;
/* background-color: black; */
/* */
background: rgba(0, 0, 0, .6);
font-size: 18px;
}
</style>
</head>

<body>
<div>小花猫,喵喵喵~</div>
</body>

</html>

CSS篇十——(3)_背景图片_03

8. 背景总结

属性

作用


background-color

背景颜色

预定义的颜色值/十六进制/RGB代码

background-image

背景图片

url(图片路径)

background-repeat

背景平铺

repeat/no-repeat/repeat-x/repeat-y

background-position

背景位置

length/position 分别是x 和 y坐标

background-attachment

背景附着

scroll(背景滚动)/fixed(背景固定)

背景简写

书写更简单

背景颜色 背景图片地址 背景平铺 背景滚动 背景位置;

背景色半透明

背景颜色半透明

background: rgba(0,0,0,0.3); 后面必须是4个值

背景图片:实际开发常见于logo或者一些装饰性的小图片或者是超大的背景图片,优点是非常便于控制位置(精灵图也是一种运用场景)

举报

相关推荐

0 条评论