Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

css - How do I go about making a re-usable button in svelte?

I would like to make a re-usable button component where I can change the color for instance. Let's say I have a base button but I want to override some properties (could be more than the background color. Ideas?

//Button.svelte
<script>
    export let backgroundColor;
</script>

<style>
 button {
   padding: 15px 20px;
   margin: 10px;
   background-color: #9174eb;  <-- I want this to be dynamic
   color: white;
   border-radius: 15px;
   box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
 }

 button:hover {
  background-color: #A78BFA; <-- This as well, and if possible based on the backgroundColor value (i don't want to use sass or anything like that) 
 }
</style>


<button style="background-color : {backgroundColor}" on:click on:mouseover>
  <slot></slot>
</button>

style="background-color : {backgroundColor}" has its limitations, for instance I cannot target the hover. And with svelte we can't inject js variables in the stylesheets...

question from:https://stackoverflow.com/questions/65916550/how-do-i-go-about-making-a-re-usable-button-in-svelte

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I like to use CSS custom properties for this.

<!-- Button.svelte -->
<script>
    export let backgroundColor;
</script>

<style>
    button {
        background-color: var(--backgroundColor);
    }
    
    button:hover {
        filter: brightness(95%);
    }
</style>

<button style="--backgroundColor: {backgroundColor}">
    <slot></slot>
</button>

This component can be used like so.

<script>
    import Button from './Button.svelte';
</script>

<Button backgroundColor="lightgreen">
    Button
</Button>
<Button backgroundColor="#ffaaff">
    Button
</Button>
<Button backgroundColor="hsla(170, 45%, 45%, 1)">
    Button
</Button>

A proposed Svelte feature will make this easier.

I apply a CSS filter on hover so the hover color is slightly darker than the background color. See this Stack Overflow answer for some other pure CSS options.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...