Conditional CSS for Svelte, but with dynamic values

Viewed 25

As I am diving into making many UI components for my Svelte apps, it seems like it’s really hard to avoid inline styling in CSS, especially when it comes to dynamic values like width, background-color, or font sizes. It’s no big deal as the guide seems to do so (https://svelte.dev/tutorial/dimensions), but not very pleasant to see all the inline styling in the HTML. I also thought of using css variables(https://svelte.dev/repl/bb42c17d585b4236824e1d5e48fe92b5?version=3.38.0) , but it gets complicated as the component gets larger, and complex.

I looked up on the HTML of documentation on the Sveltekit website. Surprisingly, they don’t have any inline CSS, all is the classes, well-organized, no inline styling whatsoever. Is there something I am missing form the documentation? I want to know how they would even make it possible to zip the dynamic values into the classes, never use the inline styling.

1 Answers

You might have some wrong assumptions here. You can look at the source code of the SvelteKit documentation on Github; there is nothing particularly special about it.

It mostly uses CSS variables, toggles various classes with class: or just has hard coded values in the classes.

Here are two example rules from the search:

label {
    color: #666;
    position: absolute;
    top: calc(50% - 0.9rem);
    right: 0;
    width: 100%;
    text-align: right;
    pointer-events: none;
    font-size: 1.2rem;
    text-transform: uppercase;
    animation: fade-in 0.2s;
}

kbd {
    display: none;
    background: #eee;
    border: 1px solid #ddd;
    padding: 0.2rem 0.2rem 0rem 0.2rem;
    color: #666;
    font-size: inherit;
    font-family: inherit;
    border-radius: 2px;
}

There is nothing dynamic about this.

Related