#get url of assets

7 messages · Page 1 of 1 (latest)

quaint quail
#

import ast from "@/assets/img.webp"

I want to access the url of this file so i can use it in the css background-image: url() property

finite nightBOT
#

Hi @quaint quail. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

You can access the URL of a local image imported from src/ using the .src property of the imported image object. Here's how to use it for a CSS background-image:

---
import myBackground from "@/assets/img.webp";
---

<div style={`background-image: url(${myBackground.src});`}>
  <slot />
</div>

Alternatively, if you want an optimized version of the image (e.g., converted to a specific format), you can use getImage(): [getImage reference]

---
import { getImage } from "astro:assets";
import myBackground from "@/assets/img.webp";

const optimizedBackground = await getImage({ src: myBackground, format: "webp" });
---

<div style={`background-image: url(${optimizedBackground.src});`}>
  <slot />
</div>

The .src property on the imported image gives you the resolved URL string, which is exactly what you need for the url() CSS function. [display unprocessed images]

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@quaint quail Kapa.ai is still learning and improving, please let me know how I did by reacting below.

quaint quail
#

@finite night do it using tailwind v4 now

finite nightBOT
#

Let me check the knowledge base for you again. One moment! :books:

#

Based on the previous conversation, you want to apply a background image using Tailwind v4. However, the knowledge sources do not contain specific information about using dynamic image URLs with Tailwind v4's CSS-in-JS or utility approach.

What I can confirm from the knowledge sources is how to set up Tailwind v4 in Astro [Tailwind guide] and how to get the image URL (as shown in the previous answer). You can combine both:

  1. Get the image URL in your frontmatter as before.
  2. Apply it via an inline style attribute (since Tailwind v4 doesn't support arbitrary dynamic values like runtime URLs in utility classes).
---
import { getImage } from "astro:assets";
import myBackground from "@/assets/img.webp";

const optimizedBackground = await getImage({ src: myBackground, format: "webp" });
---

<div
  class="w-full h-screen bg-cover bg-center"
  style={`background-image: url(${optimizedBackground.src});`}
>
  <slot />
</div>

Here, Tailwind v4 utility classes (e.g., bg-cover, bg-center) handle the background sizing/positioning, while the dynamic background-image: url(...) is applied via the inline style attribute — since the image URL is a runtime value that can't be expressed as a static Tailwind class. [getImage reference]

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: