#Styling slot children with :global - is this possible?

3 messages · Page 1 of 1 (latest)

civic sparrow
#

Hi there,

Say I've this component

<SectionBreak id='section-2' paragraph='this is a paragraph'>
<div slot='title'>
<h2>Title over <span>two lines</span></h2>
</div>
</SectionBreak>

The inside of my component looks like this:

<section >
<div class='text-content'>
<slot name='title' />
{paragraph && <p>{paragraph}</p>}
</div>
</section>

Then for my SCSS, I really want to just do this...

section {
    :global(.text-content) {
        h2 {
            color: red;
        }

        span {
            color: orange;
        }

        p {
            color: green;
        }
    }

Is there any way to get something like this working?

frail quailBOT
#

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

#

Yes, it is possible to style slot children using the :global() selector in Astro. The :global() selector allows you to apply styles to elements that live outside of the current component.

In your case, you can use the :global() selector to style the h2, span, and p elements that are children of the .text-content class. Here's how you can do it:

section {
    .text-content {
        :global(h2) {
            color: red;
        }

        :global(span) {
            color: orange;
        }

        :global(p) {
            color: green;
        }
    }
}

This will apply the styles to the h2, span, and p elements that are children of the .text-content class, regardless of whether they are in the same component or not.

Please note that the :global() selector should be used sparingly and only when necessary, as it can make your styles harder to manage and troubleshoot. It's generally recommended to use scoped styles as much as possible, and only use global styles as needed.

For more information, you can refer to the Astro documentation on global styles (https://docs.astro.build/en/guides/styling#global-styles) and the Astro documentation on the :global() selector (https://docs.astro.build/en/reference/directives-reference#script--style-directives).

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