教程 css tutorial

背景属性

CSS 的背景属性用于控制元素的背景表现,包括颜色、图片、位置、大小和是否重复等。

1. 背景颜色(background-color)

设置元素背景颜色:

css
background-color: #f0f0f0;

2. 背景图片(background-image)

为元素设置背景图片:

css
background-image: url("bg.jpg");

3. 背景位置(background-position)

控制背景图片的位置:

css
background-position: center;
background-position: 10px 20px;

4. 背景大小(background-size)

控制背景图片的大小:

css
background-size: cover; /* 充满容器 */
background-size: contain; /* 保持比例完整显示 */
background-size: 100px 50px; /* 指定宽高 */

5. 背景重复(background-repeat)

控制背景图片是否重复:

css
background-repeat: no-repeat;
background-repeat: repeat-x;
background-repeat: repeat-y;
background-repeat: repeat;

背景属性示例

在线代码演示
源码
<!DOCTYPE html>
<html lang="zh-CN">

<head> <meta charset="UTF-8" /> <title>背景属性示例</title> <style> .bg-color { background-color: #f0f0f0; padding: 20px; margin-bottom: 10px; border: 1px solid #ccc; }

.bg-image {
  background-image: url('https://via.placeholder.com/150');
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
  height: 150px;
  border: 1px solid #ccc;
  margin-bottom: 10px;
}

.bg-repeat {
  background-image: url('https://via.placeholder.com/50');
  background-repeat: repeat;
  height: 100px;
  border: 1px solid #ccc;
  margin-bottom: 10px;
}

</style> </head>

<body> <div class="bg-color">背景颜色示例(浅灰色背景)</div> <div class="bg-image">背景图片示例(居中、不重复、contain)</div> <div class="bg-repeat">背景图片示例(重复平铺)</div> </body>

</html>