CSS 可以添加背景颜色和背景图片,以及来进行图片设置。
background-color | 背景颜色 |
---|---|
background-image | 背景图片地址 |
background-repeat | 是否平铺 |
background-position | 背景位置 |
background-attachment | 背景固定还是滚动 |
背景的合写(复合属性) | |
background:背景颜色 背景图片地址 背景平铺 背景滚动 背景位置 |
语法:
background-image : none | url (url)
参数:
none : 无背景图(默认的) url : 使用绝对或相对地址指定背景图像
background-image 属性允许指定一个图片展示在背景中(只有CSS3才可以多背景)可以和 background-color 连用。 如果图片不重复地话,图片覆盖不到地地方都会被背景色填充。 如果有背景图片平铺,则会覆盖背景颜色。
小技巧: 我们提倡 背景图片后面的地址,url不要加引号。
语法:
background-repeat : repeat | no-repeat | repeat-x | repeat-y
参数:
repeat : 背景图像在纵向和横向上平铺(默认的)
no-repeat : 背景图像不平铺
repeat-x : 背景图像在横向上平铺
repeat-y : 背景图像在纵向平铺
语法:
background-position : length || length
background-position : position || position
参数:
length : 百分数 | 由浮点数字和单位标识符组成的长度值。请参阅长度单位 position : top | center | bottom | left | center | right
说明:
设置或检索对象的背景图像位置。必须先指定background-image属性。默认值为:(0% 0%)。 如果只指定了一个值,该值将用于横坐标。纵坐标将默认为50%。第二个值将用于纵坐标。
注意:
实际工作用的最多的,就是背景图片居中对齐了。
body {
background-image: url(images/bg.jpg);
background-repeat: no-repeat;
/* 只给定一个,另一个默认居中 */
background-position: top;
}
语法:
background-attachment : scroll | fixed
参数:
scroll : 背景图像是随对象内容滚动 fixed : 背景图像固定
说明:
设置或检索背景图像是随对象内容滚动还是固定的。
background属性的值的书写顺序官方并没有强制标准的。为了可读性,建议大家如下写:
background:背景颜色 背景图片地址 背景平铺 背景滚动 背景位置
background: transparent url(image.jpg) repeat-y scroll 50% 0 ;
<style>
body {
/* background-image: url(images/bg.jpg); */
/* background-repeat: no-repeat; */
/* background-position: center top; */
color: #ffffff;
font-size: 20px;
/* 设置背景图固定 */
/* background-attachment: fixed; */
/* 设置背景图滚动 */
/* background-attachment: scroll; */
/* 复合写法(简写) */
background: #888888 url(images/bg.jpg) no-repeat fixed center top;
}
</style>
CSS3支持背景半透明的写法语法格式是:
background: rgba(0,0,0,0.3);
最后一个参数是alpha 透明度 取值范围 0~1之间
注意: 背景半透明是指盒子背景半透明, 盒子里面的内容不受影响。
通过background-size设置背景图片的尺寸,就像我们设置img的尺寸一样,在移动Web开发中做屏幕适配应用非常广泛。
其参数设置如下:
a) 可以设置长度单位(px)或百分比(设置百分比时,相对于父盒子的宽高)
b) 设置为cover时,会自动调整缩放比例(等比例拉伸),保证图片始终填充满背景区域(直到宽和高都填满,可能会溢出),如有溢出部分则会被隐藏。我们平时用的cover 最多
c) 设置为contain会自动调整缩放比例(等比例拉伸),保证图片始终完整显示在背景区域(宽或者高有一方填满就不再继续拉伸),可能有空白区域。
background-image: url('images/gyt.jpg');
background-size: 300px 100px;
/* background-size: contain; */
/* background-size: cover; */
background-size:300px ; 只写一个参数时肯定是宽度,高度省略会等比例缩放
以逗号分隔可以设置多背景,可用于自适应布局 做法就是 用逗号隔开就好了。
background:url(test1.jpg) no-repeat scroll 10px 20px/50px 60px ,
url(test1.jpg) no-repeat scroll 10px 20px/70px 90px ,
url(test1.jpg) no-repeat scroll 10px 20px/110px 130px c #aaa;
语法1: background: linear-gradient(起始方向,颜色1,眼色,……);
background: -webkit-linear-gradient(left, red, blue);
background: -webkit-linear-graident(left top,red ,blue);(起始方向为左上角)
背景渐变必须添加浏览器私有前缀
起始方向可以是:方位名词或度数,如果省略默认为top
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有