home ~ projects ~ socials

Using A Custom Element As A Styling Wrapper

This post is designed to confirm you can target a custom element with a CSS selector to style both it and it's children (e.g. in a grid).

Output

Sidebar
Main Content

HTML

<custom-test-wrapper>
  <div>Sidebar</div>
  <div>Main Content</div>
</custom-test-wrapper>

CSS

custom-test-wrapper {
  border: 1px solid red;
  display: grid;
  gap: 1rem;
  grid-template-columns: 12ch 1fr;
}

custom-test-wrapper div {
  padding: 1rem;
}

custom-test-wrapper div:first-child {
  border-right: 1px solid green;
}

The reason I'm doing this is to support a code block web component where it would be nice to be able to style the custom element for the main wrapper instead of having to add a

inside it for that sole purpose.

I've tested it in Firefox, Safari, and Chrome on a mac and everything looks good. I've also gotten some confirmation in the Frontend Horse discord that things should basically work as expected in the light DOM. (Introducing the shadow DOM could change things, but I'm not doing that in my current component.)

-- end of line --