borodean / postcss-assets

An asset manager for PostCSS
MIT License
537 stars 32 forks source link

Get negative image width/height #60

Closed georgest closed 7 years ago

georgest commented 7 years ago

How can I get image width or height with negative sign. For example I want to achieve this:

margin-left: -width('image.jpg');

But it is not rendered properly.

borodean commented 7 years ago

Hey @georgest! I see two ways of how to achieve that. It doesn't seem to me that any of this ways is perfectly clean though. Hope this could be made cleaner as soon as PostCSS ecosystem develops.

Option 1. Use expression-reducing plugins (like postcss-calc) to multiply the result by -1:

postcss([
  require('postcss-assets'),
  require('postcss-calc'), // included after postcss-assets
]);
body {
  margin-left: calc(-1 * width('image.jpg'));
}

The calc() expression gets reduced and the resulting CSS contains exactly what you want.

Option 2. Provide function with negative density argument:

body {
  margin-left: width('image.jpg', -1);
}

This feels a little bit like a hack since that's clearly not the purpose of the density argument. However, since all it does is divides the dimension by itself it results in what you want.

borodean commented 7 years ago

@andyjansson do you think it is a valid way to handle postcss-functions function output?

andyjansson commented 7 years ago

Personally, I'd go for the first option as to avoid ambiguity. width('image.jpg', -1) relies on an undocumented implementation detail and there's no guarantee that the implementation will remain the same. What's more, the first option probably falls better in line with the whole "do-one-thing" philosophy that postcss has got going.