Z
ZHANK

背景图像

background-image、背景重复/位置/大小、全屏背景

背景图像

用 CSS background-image 给元素设置背景图——比 <img> 更灵活,可以叠加文字。

学完本章你将: 掌握 background-image、背景重复/位置/大小、全屏背景。


基本背景图

html
<div style="background-image: url('bg.jpg'); height: 300px;">
  <h2>这是叠加在背景上的文字</h2>
</div>

<!-- 也可以用于整个页面 -->
<body style="background-image: url('bg.jpg');">

背景控制

html
<style>
  .bg-box {
    width: 400px;
    height: 300px;
    background-image: url('pattern.png');

    /* 不重复 */
    background-repeat: no-repeat;

    /* 覆盖整个容器 */
    background-size: cover;

    /* 居中定位 */
    background-position: center;

    /* 固定不随滚动 */
    background-attachment: fixed;
  }
</style>

背景简写

html
<div style="background: url('bg.jpg') no-repeat center/cover; height: 400px;">
  <h1 style="color: white; text-align: center; padding-top: 150px;">
    全屏 Hero 背景
  </h1>
</div>

渐变背景

html
<!-- 线性渐变 -->
<div style="background: linear-gradient(to right, red, yellow); height: 100px;">

<!-- 径向渐变 -->
<div style="background: radial-gradient(circle, red, yellow, green); height: 100px;">