ข้ามไปยังเนื้อหา

Styles

React ไม่มีระบบ scope CSS มาในตัว — คุณต้องเลือกระหว่าง CSS Modules, Styled Components, Tailwind หรือ global CSS ธรรมดา ส่วนบล็อก <style> ของ Svelte ถูก scope ให้ component โดยอัตโนมัติ: ทุก selector จะได้ attribute ที่ไม่ซ้ำกันฉีดเข้าไปตอน build ดังนั้น .button ใน component หนึ่งจึงไม่มีทางชนกับ .button ในอีก component หนึ่ง ไม่ต้อง config อะไรเลย

React (CSS Modules)
// Button.module.css
.button { background: #FF3E00; color: white; padding: 0.5rem 1rem; }
// Button.jsx
import styles from './Button.module.css';
function Button({ label }) {
return <button className={styles.button}>{label}</button>;
}
Svelte
<!-- Button.svelte -->
<script>
let { label } = $props();
</script>
<button>{label}</button>
<style>
/* This .button only applies inside this component */
button { background: #FF3E00; color: white; padding: 0.5rem 1rem; }
</style>

Svelte compile บล็อก <style> แล้วเพิ่ม attribute ที่ผ่านการ hash และไม่ซ้ำกันให้กับทุก element ที่ถูกแตะโดย style นั้น (เช่น <button class="svelte-xyz123">) selector จะกลายเป็น button.svelte-xyz123 — ไม่ซ้ำกันทั้งโปรเจกต์ ไม่มีทางชนกันได้

โดยทั่วไป React developer มักจะ toggle class ด้วย ternary หรือ library อย่าง clsx ส่วน Svelte มี directive class: มาให้แบบ first-class:

React
function Alert({ message, type = 'info' }) {
return (
<div className={`alert alert--${type}`}>
{message}
</div>
);
}
// With boolean toggle:
<div className={isActive ? 'box box--active' : 'box'}>
Svelte
<script>
let { message, type = 'info' } = $props();
let isActive = $state(false);
</script>
<div class="alert alert--{type}">{message}</div>
<!-- Boolean class toggle — no clsx needed: -->
<div class="box" class:box--active={isActive}>...</div>

class:name={condition} จะเพิ่ม name เข้าไปใน class list ของ element เมื่อ condition เป็น truthy และเอาออกเมื่อไม่ใช่ สะอาด อ่านง่าย ไม่ต้องต่อ string

บางครั้งคุณจำเป็นต้อง target element ลูก หรือใส่ style แบบ global จริง ๆ ให้ใช้ :global():

<style>
/* Scoped — only affects elements in this component */
.container { padding: 1rem; }
/* Global — applies everywhere */
:global(body) { margin: 0; }
/* Scoped parent, global child */
.container :global(a) { color: #FF3E00; }
</style>
selector CSS ภายในบล็อก <style> ของ Svelte จะเป็นอย่างไร?
คุณเพิ่ม CSS class แบบมีเงื่อนไขใน Svelte โดยไม่ต้องต่อ string อย่างไร?
คุณเขียน CSS rule แบบ global จริง ๆ ภายในบล็อก <style> ของ Svelte อย่างไร?
อะไรคือแนวทางที่แนะนำสำหรับ theming แบบ dynamic ใน Svelte เมื่อ scoped style อ้างอิง runtime JS ไม่ได้?