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.
<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.
<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.
- Global Styles: Define these in your main CSS/SCSS files (e.g.,
src/scss/main.scss) and include them in your layout or page templates. These styles apply to the entire document. - Component Styles: Define these within the
<template>tag using a<style>block. These are specific to the component and are automatically scoped.
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.