#get url of assets
7 messages · Page 1 of 1 (latest)
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.
@finite night do it using tailwind v4 now
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:
- Get the image URL in your frontmatter as before.
- Apply it via an inline
styleattribute (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>