streamich / nano-css

Distilled CSS-in-JS for gourmet developers
The Unlicense
427 stars 23 forks source link

Addon for vertical/horizontal #231

Closed zaytri closed 5 years ago

zaytri commented 5 years ago

Would you be able to add an addon to support horizontal and vertical for margin and padding? It would be used like:

{
  marginHorizontal = '20px'
}

Which would be equivalent to:

{
  marginLeft = '20px',
  marginRight = '20px'
}

And vertical would be used for both top and bottom values. Could even add them to atoms with v and h. I'm just used to using those in React Native and I would love to see support for it in here!

zaytri commented 5 years ago

I guess it's not too necessary to have it as an addon it's pretty simple to implement externally.

const customCss = css => {
  const {
    marginVertical, marv,
    marginHorizontal, marh,
    paddingVertical, padv,
    paddingHorizontal, padh,
  } = css

  const mv = marginVertical || marv
  const mh = marginHorizontal || marh
  const pv = paddingVertical || padv
  const ph = paddingHorizontal || padh

  if (mv) { css.marginTop = mv; css.marginBottom = mv }
  if (mh) { css.marginLeft = mh; css.marginRight = mh }
  if (pv) { css.paddingTop = pv; css.paddingBottom = pv }
  if (ph) { css.paddingLeft = ph; css.paddingRight = ph }

  return css
}

export const jsx = (component, css, name) => nano.jsx(component, customCss(css), name)

This is my solution for it and it gets the job done. Not sure if there's a better way to write it? But it works.

streamich commented 5 years ago

You can just set margin and padding:

css.margin = `${mv} ${mh}`;
css.padding = `${pv} ${ph}`;
zaytri commented 5 years ago

Ah yes I forgot about that shorthand thank you! Here's an updated version of that customCss function then, along with support for unitless: (It also now removes the horizontal/vertical keys from the return value)

const customCss = css => {
  const {
    marginVertical, marv,
    marginHorizontal, marh,
    paddingVertical, padv,
    paddingHorizontal, padh,
    ...newCss
  } = css

  const [mv, mh, pv, ph] = [
    marginVertical || marv,
    marginHorizontal || marh,
    paddingVertical || padv,
    paddingHorizontal || padh
  ].map(style => {
    if (!style) return 0
    if (Number.isInteger(style)) return `${style}px`
  })

  if (mv || mh) { newCss.margin = `${mv} ${mh}` }
  if (pv || ph) { newCss.padding = `${pv} ${ph}` }

  return newCss
}