Component best practice. How to allow different methods of positioning for components

Viewed 34

Lets say i have a reusable component that i want to place at an absolute position but i also want to allow it to be placed inside eg. flex-boxes. What is the intended workflow for this since i cannot easily pass styles to child components? I know i can use the .parent :global(.child) pattern but this seems like an ugly way of solving the issue but the best i have found. I could also habitually wrap components inside style wrappers to give them absolute positions but this also seems like a blunt way of approaching it. I am thinking i might need to change my mindset on how to approach the problem so i am open to both specific feedback and feedback on how to approach thee issue in a different way.

This REPL demonstrates the issue https://svelte.dev/repl/da3cd9b8b8f54cd7b0bfac958d1b938e?version=3.46.2

2 Answers

Unless you add a series of properties to your component to do so this is is not possible. And positioning itself is not really the task of the component is it ?

So your best options are doing the positioning from outside the component by wrapping the component. Or if you want allow the users to pass a css class to the component and apply it correctly, beware that this class still has to be marked as global of course.

Aside from using a wrapper, using inline-styles does not seem like that big of an evil here. Positioning information is not something that usually requires lower specificity so it can be overridden.

For generic components like buttons I tend to apply the $$restProps which would also allow just setting style.

<MyButton style="position: absolute; left: 20px; top: 40px;"/>
<!-- MyButton.svelte -->
<button {...$$restProps}>
    MyButton
</button>
Related