#CSS Selector for direct children of used layout

3 messages · Page 1 of 1 (latest)

celest tundra
#

Hi Astro,

I'm very new to astro, so it could very well be that I'm misusing some concepts. In short, what I'm currently trying to do: Apply styles to direct descendants of the layout I'm using for a page.

This is my setup:
I have a BaseLayout, and its stripped contents are:

---
import Header from "../components/Header.astro";
import Footer from "../components/Footer.astro";
import "../styles/global.css";
---
<html>
    <head>...</head>
    <body>
        <Header />

        <main>
                        <!-- I'm trying to style the slotted contents -->
                        <!-- So the direct descendants of the main element -->
            <slot />
        </main>

        <Footer />
    </body>
</html>

Now my (stripped) index page looks as follows:

---
import BaseLayout from "../layouts/BaseLayout.astro";

---

<style>
    & > div {
        padding-inline: 2rem;
        outline: 2px solid red;
    }
</style>

<BaseLayout >
<!-- Trying to write a css selector for these top-level divs here -->
<div>Section 1...</div>
<div>Section 2...</div>
</BaseLayout>

Now I would like to apply some styles only to the 'top-level' divs inside the BaseLayout. How do I go about this? I've tried adding selectors based on the parent, but this of course doesn't work, since the styles are scoped. Maybe I have the wrong division between what is part of my BaseLayout and what is part of the styling of the contents?

Kind regards,
Auke

orchid violet
#

Hi ! If you want the CSS rule to be applied on all pages using the BaseLayout, maybe you can move the declaration inside the src/styles/global.css file, like :

main > div {
  padding-inline: 2rem;
  outline: 2px solid red;
}

Then all your pages will define content that will go inside the <main> tag from your BaseLayout and the styles should be applied for all of them, I think

gilded dove
#

What BeatGrinder as suggested, or you can keep the styles in BaseLayout if you prefer by using :global(> div), so something like:

<style>
 main :global(> div) {
  /* your styles for top level div inside main */
 }
</style>

See the second code snippet in https://docs.astro.build/en/guides/styling/#global-styles

Docs

Learn how to style components in Astro with scoped styles, external CSS, and tooling like Sass and PostCSS.