背景
在 CSS 中,背景(background)属性用于设置元素的背景样式,包括背景颜色、背景图片、背景平铺方式等。
笔记内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>背景</title>
<style>
.content{
/* 设置背景颜色 */
background-color: green;
/* 设置背景图片 */
/* 如果不设置 background-repeat ,则默认水平垂直平铺 */
background-image: url("logo.png");
/* 设置背景图片大小 */
/* 背景图片不会撑开盒子,只有 img 里的图片才会撑开盒子 */
background-size: 300px 200px; /* 设置背景图片 width300px,height200px */
background-size: 300px; /* 设置背景图片大小,如果只有一个值,那另一个跟着等比缩放 */
background-size: auto; /* 设置背景图片的大小,auto:自动大小;40% 60%:用百分比设置背景图片大小;cover:填充整个块元素,如有溢出则被隐藏;contain:等比缩放填充块元素,可能填充不完全 */
/* 设置背景图片位置:以父盒子作为参考 */
/* 只要用了 px,或者百分比,就必须水平在前,垂直在后,哪怕其中有一个用的是 center 之类的关键词 */
background-position: 12px 50px; / *必须水平在前,垂直在后:背景图片水平向右移动 12px,垂直向下移动50px;一般使用精灵图就用这个属性控制 */
background-position: 30% 50%; /* 必须水平在前,垂直在后:背景图片水平向右移动父元素的 30%,垂直向下移动父元素的 50% */
background-position: center top;/* 用关键词设置背景图片的位置(可以先设置水平,也可以先设置垂直),水平方向:left、center、right,垂直反向:top、center、bottom */
background-position: left; /* 如果只写一个值,另外一个默认居中:写 left 和 right 则垂直方向居中;写 top 和 bottom 则水平方向居中 */
/* 设置背景图片平铺方式 */
background-repeat: no-repeat; /* 背景图片:no-repeat 不平铺,repeat-x 水平方向平铺,repeat-y 垂直方向平铺,repeat 水平垂直都平铺 */
/* 设置背景图片固定方式 */
background-attachment: scroll; /* 背景图片是否随着页面滚动:scroll 滚动(默认的),fixed 不滚动(固定) */
/* 一次性设置背景图片的顺序(顺序没有强制要求,但建议以这个顺序):背景颜色、背景图片地址、背景平铺、背景滚动、背景位置 */
background: red;
background: url("logo.png") no-repeat;
background: green url("logo.png") no-repeat fixed center top;
/* 设置同时有两个背景图片,但是显示的位置不同(多背景时,颜色代码要写在下面,防止颜色把背景图片覆盖),这是 CSS3 中的功能 */
background: url("logo.png") no-repeat left top,url("logo.png") no-repeat right bottom;
/* 设置背景透明度:这是 CSS3 中的功能,低版本的浏览器不支持 */
/* rgba 指:red green blue alpha(透明度) */
background: rgba(0,0,0,0.3); /* 设置背景透明度:前面三个值是 rgb 的颜色值,最后一个是透明度(范围 0~1,1 不透明) */
/* 背景渐变 */
background: -webkit-linear-gradient(top,red,yellow); /* background:-webkit-linear-gradient(渐变的起始位置,起始颜色,结束颜色),添加 -webkit- 是为了兼容浏览器 */
background: -webkit-linear-gradient(top,red 0%,green 50%,blue 100%); /* background:-webkit-linear-gradient(渐变的起始位置,颜色 位置,颜色 位置,颜色 位置),添加 -webkit- 是为了兼容浏览器 */
}
</style>
</head>
<body>
<div class="content">
123
</div>
</body>
</html>