tailwind-css
  1. tailwind-css-background-position

Tailwind CSS Background Position

Tailwind CSS provides a number of utility classes for setting the position of an element's background image. These classes allow you to control the horizontal and vertical positioning of the background image, as well as whether it is repeated, sized and more.

Syntax

The syntax for using the Tailwind CSS background position utility classes is as follows:

<div class="bg-{position}-{y axis}-{x axis}"></div>

Here, {position} represents one of nine common background positions, {y axis} represents the vertical positioning of the background image (optional), and {x axis} represents the horizontal positioning of the background image (optional).

Example

Here we have an example of a container with a background image centered in the middle.

<div class="bg-center bg-cover bg-no-repeat w-full h-screen" style="background-image: url('https://images.unsplash.com/photo-1605503949519-0e3c6feda2c0')">
  <h1 class="text-white text-4xl font-bold text-center">Welcome to my website!</h1>
</div>

Output

The above code will produce the following output:

Tailwind CSS Background Position Example

Explanation

  • bg-center: Centers the background image horizontally and vertically.
  • bg-cover: Resizes the image proportionally to cover the entire container while maintaining its aspect ratio.
  • bg-no-repeat: Prevents the image from being repeated.
  • w-full: Sets the width of the element to full width of its container.
  • h-screen: Sets the height of the element to full height of the viewport.

Use

The bg-{position} classes can be used to control the position of the background image for elements with a background image set using the background-image CSS property.

Important Points

  • {position} can be any of the following class names: bottom, center, left, left-bottom, left-top, right, right-bottom, right-top, top.
  • {y axis} and {x axis} can be added as optional modifiers to the {position} class name.
  • You can also use the object-{fit} and object-{position} classes to achieve the same result with the background-image property.

Summary

Tailwind CSS provides a number of utility classes for controlling the position of an element's background image. These classes allow you to easily control the horizontal and vertical positioning of an image as well as other properties such as sizing and repetition. By using these classes, you can quickly and efficiently style your web applications.

Published on: