Styles
React ไม่มีระบบ scope CSS มาในตัว — คุณต้องเลือกระหว่าง CSS Modules, Styled Components, Tailwind หรือ global CSS ธรรมดา ส่วนบล็อก <style> ของ Svelte ถูก scope ให้ component โดยอัตโนมัติ: ทุก selector จะได้ attribute ที่ไม่ซ้ำกันฉีดเข้าไปตอน build ดังนั้น .button ใน component หนึ่งจึงไม่มีทางชนกับ .button ในอีก component หนึ่ง ไม่ต้อง config อะไรเลย
Scoped styles
หัวข้อที่มีชื่อว่า “Scoped styles”// Button.module.css.button { background: #FF3E00; color: white; padding: 0.5rem 1rem; }
// Button.jsximport styles from './Button.module.css';function Button({ label }) { return <button className={styles.button}>{label}</button>;}<!-- 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 — ไม่ซ้ำกันทั้งโปรเจกต์ ไม่มีทางชนกันได้
Dynamic class: directive class:
หัวข้อที่มีชื่อว่า “Dynamic class: directive class:”โดยทั่วไป React developer มักจะ toggle class ด้วย ternary หรือ library อย่าง clsx ส่วน Svelte มี directive class: มาให้แบบ first-class:
function Alert({ message, type = 'info' }) { return ( <div className={`alert alert--${type}`}> {message} </div> );}
// With boolean toggle:<div className={isActive ? 'box box--active' : 'box'}><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
Global styles (เลือกที่จะไม่ scope)
หัวข้อที่มีชื่อว่า “Global styles (เลือกที่จะไม่ scope)”บางครั้งคุณจำเป็นต้อง 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>