Giter Site home page Giter Site logo

evrone / postcss-px-to-viewport Goto Github PK

View Code? Open in Web Editor NEW
2.9K 58.0 398.0 277 KB

A plugin for PostCSS that generates viewport units (vw, vh, vmin, vmax) from pixel units. The best choice to create a scalable interface on different displays by one design size.

Home Page: https://evrone.com/postcss-px-viewport

License: MIT License

JavaScript 94.62% CSS 5.38%
postcss pixel-units viewport-units vw vh css-scale mobile-design media-queries rem-units taro

postcss-px-to-viewport's Introduction

postcss-px-to-viewport

NPM version

English | 中文

A plugin for PostCSS that generates viewport units (vw, vh, vmin, vmax) from pixel units.

Demo

If your project involves a fixed width, this script will help to convert pixels into viewport units.

Input

.class {
  margin: -10px .5vh;
  padding: 5vmin 9.5px 1px;
  border: 3px solid black;
  border-bottom-width: 1px;
  font-size: 14px;
  line-height: 20px;
}

.class2 {
  padding-top: 10px; /* px-to-viewport-ignore */
  /* px-to-viewport-ignore-next */
  padding-bottom: 10px;
  /* Any other comment */
  border: 1px solid black;
  margin-bottom: 1px;
  font-size: 20px;
  line-height: 30px;
}

@media (min-width: 750px) {
  .class3 {
    font-size: 16px;
    line-height: 22px;
  }
}

Output

.class {
  margin: -3.125vw .5vh;
  padding: 5vmin 2.96875vw 1px;
  border: 0.9375vw solid black;
  border-bottom-width: 1px;
  font-size: 4.375vw;
  line-height: 6.25vw;
}

.class2 {
  padding-top: 10px;
  padding-bottom: 10px;
  /* Any other comment */
  border: 1px solid black;
  margin-bottom: 1px;
  font-size: 6.25vw;
  line-height: 9.375vw;
}

@media (min-width: 750px) {
  .class3 {
    font-size: 16px;
    line-height: 22px;
  }
}

Getting Started

Installation

Add via npm

$ npm install postcss-px-to-viewport --save-dev

or yarn

$ yarn add -D postcss-px-to-viewport

Usage

Default Options:

{
  unitToConvert: 'px',
  viewportWidth: 320,
  unitPrecision: 5,
  propList: ['*'],
  viewportUnit: 'vw',
  fontViewportUnit: 'vw',
  selectorBlackList: [],
  minPixelValue: 1,
  mediaQuery: false,
  replace: true,
  exclude: undefined,
  include: undefined,
  landscape: false,
  landscapeUnit: 'vw',
  landscapeWidth: 568
}
  • unitToConvert (String) unit to convert, by default, it is px.
  • viewportWidth (Number) The width of the viewport.
  • unitPrecision (Number) The decimal numbers to allow the vw units to grow to.
  • propList (Array) The properties that can change from px to vw.
    • Values need to be exact matches.
    • Use wildcard * to enable all properties. Example: ['*']
    • Use * at the start or end of a word. (['position'] will match background-position-y)
    • Use ! to not match a property. Example: ['*', '!letter-spacing']
    • Combine the "not" prefix with the other prefixes. Example: ['', '!font']
  • viewportUnit (String) Expected units.
  • fontViewportUnit (String) Expected units for font.
  • selectorBlackList (Array) The selectors to ignore and leave as px.
    • If value is string, it checks to see if selector contains the string.
      • ['body'] will match .body-class
    • If value is regexp, it checks to see if the selector matches the regexp.
      • [/^body$/] will match body but not .body
  • minPixelValue (Number) Set the minimum pixel value to replace.
  • mediaQuery (Boolean) Allow px to be converted in media queries.
  • replace (Boolean) replaces rules containing vw instead of adding fallbacks.
  • exclude (Regexp or Array of Regexp) Ignore some files like 'node_modules'
    • If value is regexp, will ignore the matches files.
    • If value is array, the elements of the array are regexp.
  • include (Regexp or Array of Regexp) If include is set, only matching files will be converted, for example, only files under src/mobile/ (include: /\/src\/mobile\//)
    • If the value is regexp, the matching file will be included, otherwise it will be excluded.
    • If value is array, the elements of the array are regexp.
  • landscape (Boolean) Adds @media (orientation: landscape) with values converted via landscapeWidth.
  • landscapeUnit (String) Expected unit for landscape option
  • landscapeWidth (Number) Viewport width for landscape orientation.

exclude and include can be set together, and the intersection of the two rules will be taken.

Ignoring

You can use special comments for ignore conversion of single lines:

  • /* px-to-viewport-ignore-next */ — on a separate line, prevents conversion on the next line.
  • /* px-to-viewport-ignore */ — after the property on the right, prevents conversion on the same line.

Example:

/* example input: */
.class {
  /* px-to-viewport-ignore-next */
  width: 10px;
  padding: 10px;
  height: 10px; /* px-to-viewport-ignore */
  border: solid 2px #000; /* px-to-viewport-ignore */
}

/* example output: */
.class {
  width: 10px;
  padding: 3.125vw;
  height: 10px;
  border: solid 2px #000;
}

There are several more reasons why your pixels may not convert, the following options may affect this: propList, selectorBlackList, minPixelValue, mediaQuery, exclude, include.

Use with PostCss configuration file

add to your postcss.config.js

module.exports = {
  plugins: {
    // ...
    'postcss-px-to-viewport': {
      // options
    }
  }
}

Use with gulp-postcss

add to your gulpfile.js:

var gulp = require('gulp');
var postcss = require('gulp-postcss');
var pxtoviewport = require('postcss-px-to-viewport');

gulp.task('css', function () {

    var processors = [
        pxtoviewport({
            viewportWidth: 320,
            viewportUnit: 'vmin'
        })
    ];

    return gulp.src(['build/css/**/*.css'])
        .pipe(postcss(processors))
        .pipe(gulp.dest('build/css'));
});

Contributing

Please read Code of Conduct and Contributing Guidelines for submitting pull requests to us.

Running the tests

In order to run tests, you need to install dev-packages:

$ npm install

Then run the tests via npm script:

$ npm run test

Changelog

The changelog is here.

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

Authors

See also the list of contributors who participated in this project.

License

This project is licensed under the MIT License.

Sponsors

Visit Evrone website to get more information about the projects build.

Sponsored by Evrone

Acknowledgments

postcss-px-to-viewport's People

Contributors

chernobelenkiy avatar iceapriler avatar koderfunk avatar lzm0x219 avatar msidolphin avatar njleonzhang avatar shuizhongyueming avatar weineel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

postcss-px-to-viewport's Issues

How to convert in inline style?

@evrone: For example, I have some inline styles, how do I get px to vw. eg:

<div style="width: 100px"></div>

I hope it can work:

<div style="width:13.3333vw"></div>

Especially in the react project.

Can we set different 'viewportWidth', etc. based on Media Query ?

I've seen a similar issue #32 there, the landscape* options do make sense somehow. However, that's sort of trick method which may not cover all situations directly.

Imagine, we have 3+ pieces of UI draft 750px*2000px for Mobile, 1920px * 1080px for PC, and even another 4096px * 2160px for big screen, can we config somehow like the following:

{
  mediaQuery: true,
  viewportWidth: {
   {
   maxWidth:750,
   value: 750
   },
  {
   minWidth: 751,
   maxWidth:1920,
   value: 1920
   },
  {
   minWidth:1921,
   value: 4096
   }
 }
}

Then we write in css with media querys like:

@media only screen and (max-width: 750px) {
  .section {
     width: 300
  }
}

@media only screen and (min-width: 751px) and (max-width: 1920px) {
  .section {
     width: 700
  }
}

@media only screen and (min-width: 1921px) {
  .section {
     width: 1900
  }
}

Which then convert and output accordingly:

@media only screen and (max-width: 750px) {
  .section {
     width: 40vw
  }
}

@media only screen and (min-width: 751px) and (max-width: 1920px) {
  .section {
     width: 36.458vw
  }
}

@media only screen and (min-width: 1921px) {
  .section {
     width: 46.387vw
  }
}

Is that possible please?
Thanks :)

vw calculate wrong

hi, i set viewportWidth: 375 and then run in the phone 6 simulator whose width is exactly 375, then i set font-size: 16px, but end up in 5vw, the right value should be 16 / 3.75 = 4.276. please help me out, thanks.
here's my code

'postcss-px-to-viewport': {
  viewportWidth: 375,
  viewportUnit: 'vw',
  // minPixelValue: 1,
  selectorBlackList: ['.ignore'],
},

download-3

Similar to the promotion page, there is a minimum width, on the mobile end is full screen, in the PC is centered, how to modify the configuration

1552300274(1)
我之前是自己写是这样写的如下:

(function (doc, win) {

  | var docEl = doc.documentElement,
  | resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
  | recalc = function () {
  | var clientWidth = docEl.clientWidth;
  | if (!clientWidth) return;
  | if(clientWidth>415){
  | docEl.style.fontSize = 100 * (414 / 640) + 'px';
  | }else{
  | docEl.style.fontSize = 100 * (clientWidth / 640) + 'px';
  | }
  | };
  |  
  | if (!doc.addEventListener) return;
  | win.addEventListener(resizeEvt, recalc, false);
  | doc.addEventListener('DOMContentLoaded', recalc, false);
  | })(document, window);

有没有哪个配置可以修改视图的阈值类似超过屏幕超过750就按750的来计算

why i add selectorBlackList class no working?

"postcss-px-to-viewport": {
viewportWidth: 750, // 视窗的宽度,对应的是我们设计稿的宽度,一般是750
viewportHeight: 1334, // 视窗的高度,根据750设备的宽度来指定,一般指定1334,也可以不配置
unitPrecision: 3, // 指定px转换为视窗单位值的小数位数(很多时候无法整除)
viewportUnit: 'vw', // 指定需要转换成的视窗单位,建议使用vw
selectorBlackList: ['.ignore', '.hairlines'], // 指定不转换为视窗单位的类,可以自定义,可以无限添加,建议定义一至两个通用的类名
minPixelValue: 1, // 小于或等于1px不转换为视窗单位,你也可以设置为你想要的值
mediaQuery: false // 允许在媒体查询中转换px
},

请停止使用` >=`做版本依赖

"devDependencies": {
  "jest": "^25.4.0",
  "postcss": ">=5.0.2"
},
"peerDependencies": {
  "postcss": ">=5.0.2"
}

这样使用会出现今天的问题,即 postcss 更新 version 8 导致 插件 landscape: true 时 打包报错:
TypeError: postcss.atRule is not a constructor

propList文档

"!" 和 ""可以组合使用, 例如: ['', '!font*'],将不转换font-size以及font-weight等属性;
['', '!font*']将不转化任何。应该是['', '!font']吧!

`keyframes` are not converted

px unit in @keyframes are not converted unless I config mediaQuery as true, is this a bug or something? I didn't found anything about this in doc.

my postcss.config.js :

module.exports = {
    plugins: [
        require('autoprefixer'),
        require('postcss-px-to-viewport')({
            viewportWidth: 750,
            // mediaQuery: true,
        })
    ]
};

my css :

@keyframes testmove {
    0%{
        top:100px;
    }
    100%{
        top:200px;
    }
}

and it turns to :

@keyframes testmove {
  0% {
    top: 100px;
  }
  100% {
    top: 200px;
  }
}

Is there a extension

Excuse me, is there a regressive solution, for example
input
width: 37.5 px;
output:
width: 37.5 px;
width: 1 rem;
width: 10vw;

about the compile range

I want the plugin just compile the folder './src', do not compile the folder './node_modules', because my ui component is not use same reference dimension, how should I do ?

How to restore it back?

After the success of the tutorial, there is no configuration, will automatically modify the restore to the previous css

Can not be used on the codepen

The plug-in can not be used on the codepen.

@use postcss-px-to-viewport;

body{
  font-size: 16px;
}

Codepen warning information:

'postcss-px-to-viewport' is not a valid postcss plugin.

How to use in clojurescript?

I am using reagent+hiccup+shadow-cljs in my web project, I also want to use this plugins.

There are a lot of introductions in blog, included Parcel、webpack、Gulp and so on,then how can i use in clojurescript project?

How to configure include

Can you write an example of include?
How do you write it?
I downloaded the above case of GitHub and failed to configure include

Spec for v0.1.x

  • detecting value orientation function (vertical/horizontal)
  • reading directives in css-comments around properties /\/\/\s+viewport:(enable|disable)\s+DetectDirection/
  • remove option viewportUnit: 'vw'
  • add option detectDirection: false
  • convert vertical oriented values between/around toggling DetectDirection

The viewPort idth property is not available after PostCSS-Loader 4.0

No matter how big the viewport idth setting is, the VW transformation on the page will have the same effect

const getStyleLoaders = (cssOptions, preProcessor, isNeedToView = true) => { const postCssPlugin = [ require('postcss-flexbugs-fixes'), require('postcss-preset-env')({ autoprefixer: { flexbox: 'no-2009', }, stage: 3, }), // postcssNormalize() ] isNeedToView && postCssPlugin.push([require('postcss-px-to-viewport'), { unitToConvert: 'px', viewportWidth: 320, unitPrecision: 5, propList: ['*'], viewportUnit: 'vw', fontViewportUnit: 'vw', selectorBlackList: [".ignore", ".hairlines"], minPixelValue: 1, mediaQuery: true, replace: true, exclude: [], }]) const loaders = [ require.resolve('style-loader'), { loader: require.resolve('css-loader'), options: cssOptions, }, { loader: require.resolve('postcss-loader'), options: { postcssOptions: { plugins: postCssPlugin, } }, }, ].filter(Boolean); if (preProcessor && preProcessor.length > 0) { loaders.push( { loader: require.resolve('resolve-url-loader'), }, ...preProcessor ); } return loaders; };

viewportWidth 适配两端该怎么处理?

Pc端的设计稿是1920
mobile的设计稿是750
问题:这里想要做一个判断viewportWidth在pc的时候值为1920,mobile的时候值是750;
目前的做法是:

  1. const screenWidth = /Android|webOS|iPhone|iPad|BlackBerry|iPad/i.test(navigator.userAgent) ? 750 : 1920 // node环境下无法判断终端是pc还是mobile
  2. plugins: [
    require("postcss-px-to-viewport")({
    ...
    viewportWidth : screenWidth
    ...
    ]

has config like pxtorem propList ?

link
https://www.npmjs.com/package/postcss-pxtorem

propList (Array) The properties that can change from px to rem.
Values need to be exact matches.
Use wildcard * to enable all properties. Example: ['']
Use * at the start or end of a word. (['position'] will match background-position-y)
Use ! to not match a property. Example: ['
', '!letter-spacing']
Combine the "not" prefix with the other prefixes. Example: ['', '!font']

postcss-px-to-viewport support lesss?

Does postcss-px-to-viewport support lesss? I'm using the non-converted syntax in less and found that it still converts.
postcss-px-to-viewport支持less吗?我在less中使用他的时候发现禁止转换的注释无效,它依旧给转换了

Neither using /* px-to-viewport-ignore / nor using / px-to-viewport-ignore-next / will work.
不管是使用 /
px-to-viewport-ignore / 还是使用/ px-to-viewport-ignore-next */ 都不生效

include设置无效

"postcss-px-to-viewport": {
"viewportWidth": 375,
"minPixelValue": 1,
include: [path.resolve('src/views/mobile')]
}
这样设置以后,views下面的web文件夹下面的所有vue文件还是转换成了vw,请问下这是什么原因?

how to set different 'viewportWidth'?

I have two different pages, and I want to set different viewportWidth,but I don't know how to do.

      "postcss-px-to-viewport": {
        viewportWidth: 1440,     // (Number) The width of the viewport.
        viewportHeight: 900,    // (Number) The height of the viewport.
        unitPrecision: 3,       // (Number) The decimal numbers to allow the REM units to grow to.
        viewportUnit: 'vw',     // (String) Expected units.
        selectorBlackList: ['.ignore', '.hairlines'],  // (Array) The selectors to ignore and leave as px.
        minPixelValue: 1,       // (Number) Set the minimum pixel value to replace.
        mediaQuery: false       // (Boolean) Allow px to be converted in media queries.
      }, 

And the other:

      "postcss-px-to-viewport": {
        viewportWidth: 750,     // (Number) The width of the viewport.
        viewportHeight: 1335,    // (Number) The height of the viewport.
        unitPrecision: 3,       // (Number) The decimal numbers to allow the REM units to grow to.
        viewportUnit: 'vw',     // (String) Expected units.
        selectorBlackList: ['.ignore', '.hairlines'],  // (Array) The selectors to ignore and leave as px.
        minPixelValue: 1,       // (Number) Set the minimum pixel value to replace.
        mediaQuery: false       // (Boolean) Allow px to be converted in media queries.
      }, 

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.