Styling
Styles in Solid are written in plain CSS. Vite includes CSS files imported from components, and Solid offers handy attributes for changing classes and styles based on signals.
A plain CSS file
Create the file src/components/TodoItem.css:
/* src/components/TodoItem.css */
.todo {
padding: 8px 12px;
border-bottom: 1px solid #ddd;
}
.done {
color: #888;
text-decoration: line-through;
}Import it in the component and set the class with the class attribute:
// src/components/TodoItem.jsx
import './TodoItem.css';
export default function TodoItem(props) {
return <li class="todo">{props.title}</li>;
}The list items get padding and a separator line. Classes from such a file are global: .todo affects any element on the page with that class.
classList
classList takes an object: the key is a class name, the value says whether it is on. Classes toggle reactively:
// src/components/TodoItem.jsx
import './TodoItem.css';
export default function TodoItem(props) {
return (
<li class="todo" classList={{ done: props.done }} onClick={props.onToggle}>
{props.title}
</li>
);
}Usage: <TodoItem title="Buy milk" done={true} />. A finished task gets the done class, and its text turns grey and struck through.
style
The style attribute takes a string or an object. In the object, property names are written as in CSS, with hyphens, and values are strings with units:
// src/components/Progress.jsx
export default function Progress(props) {
return (
<div style={{ background: '#eee', height: '8px' }}>
<div style={{ width: `${props.percent}%`, height: '100%', 'background-color': 'green' }} />
</div>
);
}<Progress percent={40} /> draws a bar filled to 40 percent.
CSS modules
A file ending in .module.css is a CSS module: Vite makes its class names unique so they do not clash with other components. One such file, src/App.module.css, already exists in the template.
// src/components/TodoItem.jsx
import styles from './TodoItem.module.css';
export default function TodoItem(props) {
return <li class={styles.todo}>{props.title}</li>;
}In the browser the element gets a class like _todo_1x2ab_1, and the styles from TodoItem.module.css apply only to this component.
Ways to style
| Approach | When it fits |
|---|---|
Plain .css | Page-wide styles |
.module.css | Styles of one component |
classList | Classes that depend on data |
style | Values computed in code |
Common mistake
Writing className and camelCase properties out of React habit:
// src/components/Progress.jsx
export default function Progress(props) {
// Wrong: className and backgroundColor
// return <div className="bar" style={{ backgroundColor: 'green' }} />;
return <div class="bar" style={{ 'background-color': 'green' }} />;
}In Solid the attribute is called class, and the style object uses CSS property names, just like a regular stylesheet.