Home > Enterprise >  Is it possible to have two selected classes with different designs on the same page/component?
Is it possible to have two selected classes with different designs on the same page/component?

Time:04-13

Svelte has a great tool for define design of classes but is it possible to define two different classes in one component?
I am working on the menu, which is in one component. When the page is reloaded I need to have 'selected' two buttons, one from the main menu and the second from a submenu, but it seems that even if the classes have different names and variables it activates only one of them - the first one. Is it possible to select more classes/active-buttons in one component at the same time?

CodePudding user response:

You can use several class: directives in the same component, on different elements as well as multiple times on a single element.

On a single element, you're allowed to mix & match multiple class: directives with the class= attribute. Svelte will merge the result.

All of this is supported, as demonstrated by the following code (and REPL):

<script>
    let name = 'world';
    
    let red = false
    let underline = false
    let align = "left"
</script>

<p>
    <label class:selected={red}>
        <input type="checkbox" bind:checked={red} />
        Red
    </label>
</p>

<p>
    <label class:selected={underline}>
        <input type="checkbox" bind:checked={underline} />
        Underline
    </label>
</p>

<p>
    Align
    <label class:selected={align === "left"}>
        <input type="radio" value="left" bind:group={align} />
        left
    </label>
    <label class:selected={align === "center"}>
        <input type="radio" value="center" bind:group={align} />
        center
    </label>
    <label class:selected={align === "right"}>
        <input type="radio" value="right" bind:group={align} />
        right
    </label>
</p>

<h1 
        
        class:red
        class:underline
>
    Hello {name}!
</h1>

<style>
    .red {
        color: red;
    }
    
    .underline {
        text-decoration: underline;
    }
    
    .align-left {
        text-align: left;
    }
    .align-center {
        text-align: center;
    }
    .align-right {
        text-align: right;
    }
    
    label {
        padding: .5em .5em .25em;
    }
    label.selected {
        background: lavender;
    }
</style>

Single element with multiple class directives and mixed with class attribute:

<h1 
        
        class:red
        class:underline
>
    Hello {name}!
</h1>

A same class (selected) used on multiple elements:

<p>
    <label class:selected={red}>
        <input type="checkbox" bind:checked={red} />
        Red
    </label>
</p>

<p>
    <label class:selected={underline}>
        <input type="checkbox" bind:checked={underline} />
        Underline
    </label>
</p>

There must be something else going on in your case (or I didn't understand your question).

  • Related