How do I customize margin values in unocss?

271 Views Asked by At

How do I customize the margin value

The default margins for mr mt ml mb is 1em,How can I set these margins to use 18px or 20px? I'd also like to do something similar with padding.

my: margin : 20px 0
mx: margin : 0 20px
ml : margin-left: 20px
mt: margin-top: 20px
2

There are 2 best solutions below

0
Ben On

You can do that by customizing your theme.

You can customize your spacing scale by editing theme.spacing or theme.extend.spacing in your tailwind.config.js file.

module.exports = {
  theme: {
    extend: {
      spacing: {
        '20px': '20px',
      }
    }
  }
}

Alternatively, you can customize just the margin scale by editing theme.margin or theme.extend.margin in your tailwind.config.js file.

module.exports = {
  theme: {
    extend: {
      margin: {
        '18px': '18px',
      }
    }
  }
}

Also, if you don't want to modify your theme, you can use arbitrary values for the utility classes, such as m-[20px] or my-[18px].

Resource: https://tailwindcss.com/docs/margin#customizing-your-theme

0
Anton Karpenko On

you may use next:

m-10px or m10px     -> margin: 10px
my-20px or my20px   -> margin-top: 20px; margin-bottom: 20px
mr-20px or mr20px   -> margin-right: 20px 0

if you don't want to use px in your styles OR if you want to set other sides (that are not mentioned) as 0 as: mr-20px -> margin: 0 20px 0 0

then you may use custom rules:

marginSideMap = {
  l: `0 0 0 ${value}px`,
  r: `0 ${value}px 0 0`,
  t: `${value}px 0 0`,
  b: `0 0 ${value}px`,
  y: `0 ${value}px`,
  x: `${value}px 0`,
  default: `${value}px`
}  
const formatMargin = (_, side, value) => ({
  margin: `${marginSideMap[side || 'default']`,
})

export default defineConfig({
  // ...
  rules: [
    [/^m([trblxy])?-?(\d+)$/, formatMargin],
  ],
})

it will grab any of the next value: m-20, mx20, mr-20 ... and apply this formatter.