The best VPN 2024

The Best VPS 2024

The Best C# Book

How to automatically add css prefix?

Spread the love

How to automatically add css prefix? Sometimes we need to automatically add a prefix to css, so I will share some methods to achieve this function. If you like, you can bookmark this post or share it on social media.

Automatically add css prefix method

How to automatically add prefixes to css styles.

How to automatically add css prefix?
How to automatically add css prefix?

step 1

Use the browser’s native method to create an element to get style, and get the prefix of the browser according to the created element

let elementStyle = document.createElement('div').style

step 2

There are five types of browser prefixes:

PrefixBrowser
webkitsafari, chrome browser
mozfirefox browser
oOpera browser
msie browser
No prefixstandard default
How to automatically add css prefix?

So write a method to determine the prefix of this element?

let screenPrefix = (() => {
  const prefix = {
    webkit: 'webkitTransform', // safari,chrome etc.
    Moz: 'MozTransform', // firefox
    O: 'OTransform', // Opera
    ms: 'msTransform', // ie
    standard: 'transform' // default
  }

  for (let key in prefix) {
    if (elementStyle[prefix[key]] !== undefined) {
      return key
    }
  }
  
  return false

step 3

Export a method to accept the css style that you want to add a prefix

export function addPrefix(style) {
   if (screenPrefix) {// The method of adding a prefix to return is false may be an error
     return false
   }
   if (screenPrefix ==='transform') {// Explain that there is no need to add a prefix, the default is fine
     return style
   }
   // hump naming
   return screenPrefix + style.charAt(0).toUpperCase() + style.substr(1)
}

step 4

If you need to add a prefix, just call the addPrefix() method in the file that needs to be called.

import { addPrefix } from 'common/js/dom'
const transform = addPrefix('transform')

The above is all the content shared.

Leave a Comment