Skip to main content

Advanced Component Styles

Coralite provides a powerful styling system that allows you to write scoped CSS directly within your components. This guide explores advanced styling techniques, including how scoping works and how to use modern CSS features like nesting.

Scoped Styles #

When you define styles inside a Coralite component template, they are automatically scoped to that component. This prevents styles from leaking out and affecting other parts of your application.

Coralite achieves this by adding a unique data-style-selector attribute to the component's root elements and transforming your CSS selectors to match this attribute.

HTML
Code copied!


<template id="my-button">
  <style>  
  button {
    background: blue;
    color: white;
  }
</style>
  <button>Click me</button>
</template>

The above component will be transformed during the build process. The CSS selector button becomes [data-style-selector="my-button"] button (conceptually), ensuring it only targets buttons within instances of this component.

CSS Nesting #

Coralite supports CSS nesting syntax out of the box, allowing you to write cleaner and more hierarchical styles. You can use the & selector to reference the parent selector.

The Parent Selector (&) #

The ampersand (&) refers to the parent rule's selector. It's particularly useful for pseudo-classes, pseudo-elements, and modifiers.

HTML
Code copied!
<template id="styled-card">
  <style>  
  .card {
    background: #fff;
    padding: 1rem;
    border: 1px solid #ddd;
  
    /* Hover state */
    &:hover {
      border-color: #aaa;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
  
    /* Dark theme modifier (if applying a class to the component) */
    &.dark {
      background: #333;
      color: #fff;
    }
  
    /* Nested element */
    & .title {
      font-size: 1.25rem;
      font-weight: bold;
      margin-bottom: 0.5rem;
    }
  }
</style>
  <div class="card">
    <div class="title">{{ title }}</div>
    <slot></slot>
  </div>
</template>

This nesting capability makes it easy to encapsulate all styles related to a component within a readable structure.

Global vs. Component Styles #

While component styles are scoped, you often need global styles for things like typography, resets, and utility classes.

You can use global utility classes (like Bootstrap or Tailwind) within your components alongside your scoped styles.

Using Preprocessors #

If your project is configured to use Sass or PostCSS (via coralite-scripts), these transformations occur before the component styles are scoped. This means you can use variables, mixins, and other preprocessor features directly within your component's <style> block.

Start Building with Coralite!

Use the scaffolding script to get jump started into your next project with Coralite

Copied commandline!