likes
comments
collection
share

Tailwind CSS:背景相关属性

作者站长头像
站长
· 阅读数 7

背景颜色

设置背景颜色

对应于CSS中的 background-color

使用 bg-{color} 设置背景颜色,同时可以在特定颜色之后指定颜色深浅和不透明度,如bg-sky-500/50

{color}区域可以填写Tailwind内置的颜色、亦可在tailwind.config.js中自定义,也可以直接填写16进制数值

module.exports = {
  theme: {
    extend: {
      colors: {
        'regal-blue': '#243c5a',
      },
    }
  }
}

背景图片

设置背景图

对应于CSS中的 background-image: url(" ")

使用bg-{url("...")}指定背景图像的链接。当然也可在tailwind.config.js中预先定义好url,则可使用含有语义的名称指定背景图。

module.exports = {
  theme: {
    extend: {
      backgroundImage: {
        'hero-pattern': "url('/img/hero-pattern.svg')",
        'footer-texture': "url('/img/footer-texture.png')",
      }
    }
  }
}

如上面代码所示,设置好后即可使用bg-hero-pattern指定背景图。

设置图片重复方式

对应于CSS中的 background-repeat

如需关闭图片重复,则使用bg-no-repeat指定。

如需要设置图片重复,则使用bg-repeat-{option}设置,{option}有如下选项:

  • [null]- 垂直和水平重复背景图
  • x - 仅水平重复背景图像
  • y - 仅垂直重复背景图像
  • space - 图像不会裁剪和伸长,并将第一个、最后一个图像固定在边角上,其余空隙尽可能均匀分布图像。
  • round - 仅允许图像不变或伸长,并将重复的图像重复直至没有空袭。

设置背景图片位置

对应于CSS中的 background-position

Tailwind 类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;

渐变背景

对应于CSS中的 background-image: linear-gradient()

在Tailwind中,我们可以快速为元素提供一个渐变色的背景。为此,您需要设置渐变朝向以及前后颜色。

设置渐变朝向

用法为bg-gradient-{direction}

{direction}配置项中,通过编写to-{方向}设置渐变方向,可使用的方向有

  • t - top(朝上)
  • b - bottom(朝下)
  • l - left(朝左)
  • r - right(朝右)

同时你可以组合书写,如:bg-gradient-to-br,这意味着渐变将朝向右下方。

设置色彩

通过编写from-{color}-[shades/opacity]via-{color}-[shades/opacity]to-{color}-[shades/opacity]组合指定渐变色。特殊的,可以用transparent来代替{color}以表示透明色。

请不要使用to-transparent进行透明淡出。如果没有to-{color}则会默认为透明色淡出。

这与设置背景颜色如出一辙,故也可以自定义色彩 (在taliwind.config.js中设置) 和使用16进制数值

控制渐变位置

要更好地控制渐变色标位置,则将from-{position}via-{position}to-{position}与色彩设置同时使用。

Tailwind CSS:背景相关属性

<div class="bg-gradient-to-r from-indigo-500 from-10% via-sky-500 via-30% to-emerald-500 to-90% ..."></div>

背景裁切

对应于CSS样式中的 background-clip

使用bg-clip-{option}对背景进行裁切。有如下选项:

  • border- 将背景裁切至容器大小
  • padding- 将背景裁切至内边距
  • content- 将背景裁切至容器内元素
  • text- 将背景按文字前景色裁切

小技巧:文字背景

可以将bg-clip-text配合text-transparent为颜色添上背景。

如果和bg-gradien进一步搭配,可以形成非常可观的渐变艺术字效果。

Tailwind CSS:背景相关属性

<div class="text-5xl font-extrabold ...">
  <span class="bg-clip-text text-transparent bg-gradient-to-r from-pink-500 to-violet-500">
    Hello world
  </span>
</div>

背景缩放

对应于CSS样式中的 background-size

Tailwind 类CSS效果
bg-autobackground-size: auto;保持图片默认大小
bg-coverbackground-size: cover;将图片伸展直至覆盖整个容器
bg-containbackground-size: contain;将图片等比缩放直至贴附在容器边缘