Skip to content

Tailwind CSS - 背景位置

Tailwind 的 background-position 实用工具类,以 bg-* 为前缀,允许你控制元素背景图片的位置。这对于创建结构良好的英雄区域、卡片以及其他注重图片构图的组件至关重要。

这些类设置 CSS 属性 background-position。将它们与 bg-cover 或 bg-contain 等背景尺寸实用工具类结合使用,以获得最佳效果。

类名CSS 属性效果
bg-bottombackground-position: bottom;将图片与底部边缘对齐。
bg-centerbackground-position: center;将图片水平和垂直居中。
bg-leftbackground-position: left;将图片与左侧边缘对齐。
bg-left-bottombackground-position: left bottom;将图片与左下角对齐。
bg-left-topbackground-position: left top;将图片与左上角对齐。
bg-rightbackground-position: right;将图片与右侧边缘对齐。
bg-right-bottombackground-position: right bottom;将图片与右下角对齐。
bg-right-topbackground-position: right top;将图片与右上角对齐。
bg-topbackground-position: top;将图片与顶部边缘对齐。

想象一张英雄图片,人物在右侧。在宽大的桌面屏幕上,你可能希望将图片居中。而在狭窄的移动屏幕上,你可能希望将焦点向右移动,以使人物保持在画面中。这是响应式背景位置实用工具类的完美用例。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Background Position</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
/* 为了清晰起见,我们使用 CSS 变量来设置背景图片 */
.hero-bg {
background-image: url('https://images.unsplash.com/photo-1557862921-37829c790f19?q=80&w=2071&auto=format&fit=crop');
}
</style>
</head>
<body class="bg-gray-100 p-8">
<h2 class="text-2xl font-bold mb-4 text-center">Responsive Hero Section</h2>
<p class="text-center mb-6 text-gray-600">Resize your browser to see the background position change.</p>
<div
class="hero-bg h-96 w-full rounded-lg shadow-xl
bg-cover bg-no-repeat
bg-center
sm:bg-right-top"
>
<div class="h-full w-full bg-black bg-opacity-30 flex items-end p-8 rounded-lg">
<h1 class="text-4xl font-bold text-white">Modern Web Development</h1>
</div>
</div>
<div class="mt-4 p-4 bg-blue-100 border-l-4 border-blue-500 text-blue-700">
<p class="font-bold">Explanation</p>
<p>在小屏幕上(移动优先),`bg-center` 被应用。在 `sm` (640px) 及更宽的屏幕上,`sm:bg-right-top` 会覆盖它,确保图片的主体仍然可见。</p>
</div>
</body>
</html>

现代 Tailwind 的 JIT(即时)编译器让你可以使用任意值来实现极致的控制。如果标准实用工具类不够精确,你可以在方括号中指定精确位置。

<!-- 将背景定位在距离左侧 50%,距离顶部 2rem 的位置 -->
<div class="bg-[50%_2rem] ..."></div>
<!-- 使用关键词和值 -->
<div class="bg-[center_top_1rem] ..."></div>
  • 结合尺寸调整:background-position 与 bg-cover 或 bg-contain 结合使用时最有效,以管理图片在其容器内的缩放方式。
  • 移动优先方法:为移动设备定义你的基础背景位置,并使用响应式前缀(sm:、md:、lg:)为更大的屏幕进行调整。
  • 考虑主体:选择一个位置,确保图片最重要的部分在不同设备尺寸上都可见。