Melody Documentation
  • Why Melody?
  • Quickstart
    • What is Melody?
    • Tutorial
    • Installation
  • Templates
    • Twig
    • Mounting Components
    • Keys and Loops
    • Attributes
    • CSS Classes
    • Inline Styles
    • Refs
    • CSS Modules
  • Melody-Streams
    • Basic concept
    • A Step-by-Step Walkthrough
  • MELODY-STREAMS API
    • createComponent
    • The component function
  • melody-hooks
    • Overview
    • Rules of Hooks
    • Event Handling
    • Separation of Concerns
  • melody-hooks API
    • useState
    • useAtom
    • useEffect
    • useRef
    • useCallback
    • useMemo
    • useReducer
    • usePrevious
  • melody-component
    • Overview
  • melody-hoc
    • Overview
Powered by GitBook
On this page
  • Conditional Styles
  • Styles with Dynamic Names

Was this helpful?

  1. Templates

Inline Styles

Similar to HTML attributes or HTML classes, Melody supports the usual HTML method of adding inline styles to a HTML element via the styles attribute:

<div style="left: 0; top: 4px">Lorem Ipsum</div>

In general, usage of inline styles on element is not a best practice; but, in rare cases, it can not be avoided (eg. complex animations).

Conditional Styles

Melody also supports the ternary if operator Twig method of adding inline declarations that are dependent on some other variable:

<div style="{{ leftPosition ? 'left:' ~ leftPosition ~ 'px' }}">Lorem Ipsum</div>

This works ok when you have only one or two conditional styles, but if you have a number of them (usually in complex animations or tooltips), it can begin to look a bit cramped and ugly. To help combat this, Melody also has the styles filter which is similar to, and works well with, the attrs or a classes filter:

<div style="{{ {
    'border': border,
    'top': top,
    'left': left
} | styles }}">Lorem Ipsum</div>

Example of combined usage with attrs and classes filters:

<div {{ {
    class: {
        base: 'foo',
        'foo--active': active,
        'foo--disabled': disabled,
    } | classes,
    style: {
        'border': border,
        'top': top,
        'left': left
    } | styles
} | attrs }}>Lorem Ipsum</div>

Styles with Dynamic Names

If you are using the styles filter and want to add styles whose names are wholly or partially contained within a variable, then you need to do the following:

<div style="{{ {
   'color': color,
   ('border-' ~ borderSide): border,
   (position): positionValue
} | styles }}">Lorem Ipsum</div>
PreviousCSS ClassesNextRefs

Last updated 5 years ago

Was this helpful?