hipsterstomper69
hipsterstomper69

Reputation: 355

Using TailwindCSS to fix a bg image relative to its div?

I'm using TailwindCSS and looking to place a decorative background image at the bottom-center of a grid item. However, using the bg-fixed class makes the image relative to the entire DOM.

Is there any way to fix a background image so that it's fixed to its div?

See below:

enter image description here

Upvotes: 0

Views: 563

Answers (1)

ChenBr
ChenBr

Reputation: 2612

Instead of using a fixed position, you can use an absolute position. Here's an example using the absolute positioning on the bg image fixed to panel's bottom:

<div class="flex h-screen">
  <div class="w-1/2 overflow-auto border-8 bg-green-400">
    <header class="text-center">Scrollable Content</header>
    <p class="h-[5rem] border-2">Text</p>
    <p class="h-[5rem] border-2">Text</p>
    <p class="h-[5rem] border-2">Text</p>
    <p class="h-[5rem] border-2">Text</p>
    <p class="h-[5rem] border-2">Text</p>
    <p class="h-[5rem] border-2">Text</p>
    <p class="h-[5rem] border-2">Text</p>
    <p class="h-[5rem] border-2">Text</p>
    <p class="h-[5rem] border-2">Text</p>
    <p class="h-[5rem] border-2">Text</p>
    <p class="h-[5rem] border-2">Text</p>
    <p class="h-[5rem] border-2">Text</p>
    <p class="h-[5rem] border-2">Text</p>
    <p class="h-[5rem] border-2">Text</p>
    <p class="h-[5rem] border-2">Text</p>
  </div>
  <div class="relative w-1/2 bg-pink-400">
    <header class="text-center">Decorative Panel</header>
    <div class="absolute bottom-0 right-[30%] h-[10rem] w-[10rem] border-2 bg-[url('https://c4.wallpaperflare.com/wallpaper/383/891/589/colorful-abstract-simple-wallpaper-preview.jpg')] bg-cover">Fixed Panel</div>
  </div>
</div>

<div class="h-screen border-8 bg-slate-400">Next Page...</div>

Tailwind-play


Explanation about the structure:

I split the composition into 2 divs. Each div takes 100vh (h-screen). We're going to focus on the first div.

This div is composed of 2 other divs, each taking half the screen's width (w-1/2). The first part contains scrollable content (green), and the second contains the decorative panel (pink). In the decorative panel, I placed a small panel with a background image. This bottom panel is relative to the decorative panel. The decorative panel got the relative class, and the bottom panel got the absolute class.

In order to center the bottom panel to the middle of his parent element, I used the bottom-0 right-[30%] utilities.


full image

Upvotes: 1

Related Questions