Search code examples
htmlcsstailwind-css

Tailwind arbitrary background-position values


The docs say that with the jit mode you can use arbitrary values for background positioning, giving the example:

<div class="bg-[center_top_1rem]">

But this isn't an arbitrary css value like say 80px.

Is there any documentation for this syntax?

1rem obviously offsets the top value, but how would I also offset the center? My guess of bg-[center_2rem_top_1rem] doesn't work.

I'm also surprised that something like bg-[0% 20%] doesn't work, especially as I've seen it suggested as answers to other questions.

Thanks


Solution

  • Good question. It is picking up the background position with a 3-value syntax which is documented here:

    https://developer.mozilla.org/en-US/docs/Web/CSS/background-position

    Example 1

    bg-[center_top_1rem]

    The center keyword value defines X. top keyword value defines Y, and 1rem defines the offset value for Y.

    Example 2

    [center_2rem_top_1rem]

    Your example does work, and will create the following css. It centres the image on the x-axis and then offsets by 2rem.

    .bg-\[center_2rem_top_1rem\] {
      background-position: center 2rem top 1rem;
    }
    

    Example 3

    [left_2rem_top_1rem]

    The effect is more obvious when we set the background-image to the left and then add an offset.

    Example 4

    bg-[0% 20%]

    Any spaces should use an underscore so at least it should be bg-[0%_20%] but I couldn't get it to work with percentage values. It did work with keywords bottom_right

    Here are all the examples, https://play.tailwindcss.com/uKNZ5jEcOK

    You can see the CSS created in the Utilities tab of the Generated CSS tab.