CSS背景

这篇博客详细介绍了CSS背景属性,包括background-color、background-image、background-repeat、background-attachment和background-position。通过实例展示了如何设置背景颜色、图像、重复方式、图片固定及位置,帮助读者深入理解CSS背景的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

一、CSS背景概述

二、background-color

三、background-image

 四、background-repeat

 五、background-attachment

 六、background-position


一、CSS背景概述

CSS 背景属性用于定义HTML元素的背景。

CSS 背景属性:

  • background-color
  • background-image
  • background-repeat
  • background-attachment
  • background-position

下面我们依次来学习!!!

二、background-color

background-color 属性定义了元素的背景颜色.

CSS中,颜色值通常以以下方式定义:

  • 十六进制 - 如:"#ff0000"
  • RGB - 如:"rgb(255,0,0)"
  • 颜色名称 - 如:"blue"
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>背景颜色</title> 
<style>
h1
{
	background-color:#6495ed;
}
p
{
	background-color:#e0ffff;
}
div
{
	background-color:#b0c4de;
}
</style>
</head>

<body>

<h1>CSS background-color 实例!</h1>
<div>
该文本插入在 div 元素中。
<p>该段落有自己的背景颜色。</p>
我们仍然在同一个 div 中。
</div>

</body>
</html>

运行结果:

三、background-image

background-image属性指定用作元素背景的图像

默认情况下,图像会重复,以覆盖整个元素

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>背景图</title> 
<style>
body 
{
	background-image:url('http://static.runoob.com/images/mix/paper.gif');
	background-color:#cccccc;
}
</style>
</head>

<body>
<h1>Nice to meet you!</h1>
</body>

</html>

运行结果:

 四、background-repeat

默认情况下,background-repeat属性在水平和垂直方向上都重复图像

<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-image: url("/i/css/gradient_bg.png");
  background-repeat: repeat-x;
}
</style>
</head>
<body>

<h1>Hello World!</h1>

<p>背景图像仅在水平方向上重复!</p>

</body>
</html>

运行结果:

 五、background-attachment

background-attachment属性指定背景图像是应该滚动还是固定的(不会随页面的其余部分一起滚动)

  • 滚动:background-attachment: scroll
  • 固定:background-attachment: fixed
<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-image: url("/i/photo/tree.png");
  background-repeat: no-repeat;
  background-position: right top;
  margin-right: 200px;
  background-attachment: fixed;
}
</style>
</head>
<body>

<h1>background-attachment 属性</h1>


<p>背景图像是固定的。请尝试向下滚动页面。</p>
...

<p>背景图像是固定的。请尝试向下滚动页面。</p>


</body>
</html>

固定运行结果:

滚动运行结果:

 六、background-position

在以上实例中我们可以看到页面的背景颜色通过了很多的属性来控制,为了简化这些属性的代码,我们可以将这些属性合并在同一个属性中

使用简写属性在一条声明中设置背景属性:

<!DOCTYPE html>
<html>
<head>
<style>
body {
  background: #ffffff url("/i/photo/tree.png") no-repeat right top;
  margin-right: 200px;
}
</style>
</head>
<body>

<h1>background 属性</h1>

<p>background 属性是在一条声明中指定所有背景属性的简写属性。</p>

</body>
</html>

运行结果:

 参考链接:CSS 背景 (w3school.com.cn)

11-03 1万+
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值