Background Size

Utilities for controlling the background size of an element’s background image.

Class reference

ClassProperties
.bg-autobackground-size: auto;
.bg-coverbackground-size: cover;
.bg-containbackground-size: contain;

Auto

Use .bg-auto to display the background image at its default size.

Background Size - 图1

  1. <div class="bg-auto bg-center ..." style="background-image: url(...)"></div>

Cover

Use .bg-cover to scale the background image until it fills the background layer.

Background Size - 图2

  1. <div class="bg-cover bg-center ..." style="background-image: url(...)"></div>

Contain

Use .bg-contain to scale the background image to the outer edges without cropping or stretching.

Background Size - 图3

  1. <div class="bg-contain bg-center ..." style="background-image: url(...)"></div>

Responsive

To control the size of an element’s background image at a specific breakpoint, add a {screen}: prefix to any existing background size utility. For example, adding the class md:bg-contain to an element would apply the bg-contain utility at medium screen sizes and above.

For more information about Tailwind’s responsive design features, check out the Responsive Design documentation.

  1. <div class="bg-auto sm:bg-cover md:bg-contain lg:bg-auto xl:bg-cover ..." style="background-image: url(...)"></div>

Background Size - 图4

Customizing

By default Tailwind provides utilities for auto, cover, and contain background sizes. You can change, add, or remove these by editing the theme.backgroundSize section of your config.

  1. // tailwind.config.js
  2. module.exports = {
  3. theme: {
  4. backgroundSize: {
  5. 'auto': 'auto',
  6. 'cover': 'cover',
  7. 'contain': 'contain',
  8. + '50%': '50%',
  9. + '16': '4rem',
  10. }
  11. }
  12. }

Responsive and pseudo-class variants

By default, only responsive variants are generated for background size utilities.

You can control which variants are generated for the background size utilities by modifying the backgroundSize property in the variants section of your tailwind.config.js file.

For example, this config will also generate hover and focus variants:

  1. // tailwind.config.js
  2. module.exports = {
  3. variants: {
  4. // ...
  5. - backgroundSize: ['responsive'],
  6. + backgroundSize: ['responsive', 'hover', 'focus'],
  7. }
  8. }

Disabling

If you don’t plan to use the background size utilities in your project, you can disable them entirely by setting the backgroundSize property to false in the corePlugins section of your config file:

  1. // tailwind.config.js
  2. module.exports = {
  3. corePlugins: {
  4. // ...
  5. + backgroundSize: false,
  6. }
  7. }