Giter Club home page Giter Club logo

include-media's Introduction

'At' sign

include-media Build Status

Simple, elegant and maintainable media queries in Sass

NPM badge

What?

include-media is a Sass library for writing CSS media queries in an easy and maintainable way, using a natural and simplistic syntax.

2.0 Release

As of 2.0 include-media only supports sass (dart-sass) 1.25+ and no longer supports previous implementations of sass. eg lib-sass, ruby-sass.

Why?

I spent quite some time experimenting with different libraries and mixins available out there, but eventually all of them failed to do everything I needed in an elegant way. Some of them wouldn't let me mix set breakpoints with case-specific values, others wouldn't properly handle the CSS OR operator and most of them had a syntax that I found complicated and unnatural.

include-media was the result of that experience and it includes all the features I wish I had found before, whilst maintaining a simplistic and natural syntax.

How to install

  • With npm: npm install include-media
  • With yarn: yarn add include-media
  • With Bower: bower install include-media
  • With Rails: gem 'include_media_rails' (maintained by KaoruDev)
  • Manually: get this file

Finally, include the file in your project using an @import statement.

How to use

Examples can be found here.

Plugins

  • include-media-export - Reference include-media breakpoints in JavaScript.
  • include-media-columns - Generate column classes using the BEMIT naming convention, automatically referencing include-media breakpoints.
  • include-media-spread - Calculates the difference between property values and distributes them through your include-media breakpoints.
  • flex_e_ble - Uses your include-media breakpoints to create your own flexible class naming structure on top of a flex based grid with inline-block fallback for IE8+ compatibility.
  • include-media-grid - An include-media plugin for generating grid classes based on the flex display.
  • im-to-em - A tiny function to convert include-media breakpoints from px to em.
  • include-media-hidden-classes - An include-media plugin to generate classes for hiding elements.
  • Fluid-Size: Use include-media breakepoints to provide the fit size for the device.

Learn more

Related projects

  • include-media-or - A fork of include-media with support for complex queries with logical disjunctions (maintained by Nirazul).

The authors

include-media was created by Eduardo Bouças and Kitty Giraudel. The lead maintainer is Jack McNicol.

We want to hear from you

We'll be on the lookout for your issues and pull requests — but make sure you read this before submitting any code!

License

This project is licensed under the terms of the MIT license.

include-media's People

Contributors

alex-lenk avatar alexanderalmstrom-madepeople avatar black7375 avatar dependabot[bot] avatar eduardoboucas avatar hinok avatar jackmcpickle avatar kaorudev avatar kittygiraudel avatar nathanjessen avatar prisis avatar tszarzynski avatar tyrann0us 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

include-media's Issues

Sass::SyntaxError

I'm building a Ruby on Rails application that uses the sass-rails gem for pre-compiling.

I have tried every combination of the following file naming conventions & files where the include-media file is imported:

  • _include-media.scss, include-media.scss, include-media.scss.css
  • home.css.scss, application.css.scss

As soon as I add the following line of code to a .css.scss file:

@import "include-media";

Regardless of the combination used, I get the following error:

Sass::SyntaxError at /
Invalid CSS after "  'phone'": expected ")", was ": 320px,"
(in .../app/assets/stylesheets/application.css.scss:35)

Which seems to be caused by line 35 of the include-media.scss file.

CSS Syntax error with retina declaration

If I use one of the retina examples:

body {
  @include media("retina2x", ">desktop") {
    font-size: 1rem;
  }
}

This compiles as:

@media (-webkit-min-device-pixel-ratio: 2) and (min-width: 1025px), ((min-resolution: 192dpi) and (min-width: 1025px) {
  body {
    font-size: 1rem; } 
}

Note the double parentheses before min-resolution: 192dpi which is a syntax error. Note, I don't think this error was happening in the past, only with the latest version.

2015-02-13_08-57-07

Can't commit without having ruby + scss-lint installed ?

Hello,

I just committed some file to propose a PR, and I had some trouble because I didn't have scss-lint. I checked how to install it and found I needed ruby.

I think it's a pain to install ruby + scss-lint to be able to contribute to the project. For this reason, I just search for a nodejs alternative, but didn't found one that doesn't need ruby and scss-lint gem to be installed.

What do you think about replacing scss-lint by another tool ? Do you know another tool ? There is stylelint, but I don't know if it provides all the rules needed for this project.

Unknown unit 'phone' or any other sass variable I try

I'm getting "Unknown unit x" anytime I try to pass a sass var (phone, tablet, etc.) to the media mixin.

This is literally all my sass:

@import "include-media";

@include media(">phone") {
  body {
    background-color: red;
  }
}

and here's the output I get when compiling:

WARNING: Unknown unit `phone`.
    on line 342 of bower_components/include-media/dist/_include-media.scss
    from line 314 of bower_components/include-media/dist/_include-media.scss
    from line 222 of bower_components/include-media/dist/_include-media.scss
    from line 112 of bower_components/include-media/dist/_include-media.scss
    from line 29 of stdin

If I pass a px value it works fine.

Any idea what's going on here?

This is using node-sass 3.0.0-beta.4 which uses libsass 3.2.0-beta.2

multiple static media expressions, OR rule

I've started to use susy for my grids and didn't want to drop include-media for breakpoint.
Turns out, it should be reasonably easy to make a mixin to use susy with your plugin (oddbird/susy#524).

What I stumbled over was a malfunctioning media rule when adding more than one static media expressions. Makes totally sense that it's not working since they exclude each other. It's still strange how they fail (3 min-width statements).
What I really wanted, was an OR rule.

First things first, the code:

im media-expressions:

$media-expressions: (
    // media types
    screen: 'screen',

    // width
    xs: '(max-width: #{$screen-xs-max})',
    sm: ('(min-width: #{$screen-sm-min}) and (max-width: #{$screen-sm-max})'),
    md: ('(min-width: #{$screen-md-min}) and (max-width: #{$screen-md-max})'),
    lg: '(min-width: #{$screen-lg-min})',

    // orientation
    portrait: '(orientation: portrait)',
    landscape: '(orientation: landscape)',

    // resolution
    res2x: '(min-resolution: 2dppx)',
    res3x: '(min-resolution: 3dppx)',
);

my code:

@include media('sm', 'md', 'lg') {
    .grid {
        < grid styling.. >
    }
}

output

@media (min-width: 768px) and (min-width: 992px) and (min-width: 1200px) {
    .grid {
        < grid styling.. >
    }
}

what i really want

@media (min-width:768px) and (max-width: 991px), (min-width: 992px) and (max-width: 1199px), (min-width: 1200px) {
    .grid {
        < grid styling.. >
    }
}

I know that it is far more feasible to just use breakpoints and do something like @include media('>xs'). But sometimes it's just convenient to combine media expressions with an OR rule. Especially when they're not min-width, max-width related. Is there a way to do that?

Add entry point to package.json

Bower has it, the package.json should have it too. I would create a pull-request for this, but I'm not sure how you manage the version between those two files (bower and package).

"main": "dist/_include-media.scss"

problem resolution queries

I can't get to work following resolution query with your latest version:
res2x: ('(-webkit-min-device-pixel-ratio: 2)', '(min-resolution: 192dpi)', '(min-resolution: 2.0dppx)')

The output is always the first one in the list (at least I'm thinking this is the pattern):

  @media (-webkit-min-device-pixel-ratio: 2) {...}

Name conflicts with bourbon.

The 'media' mixin conflicts with Bourbon Neat mixin with the same name.
Would you prepend to all of include-media mixins/variables/maps some prefix, e.g. smth like 'eb-' or 'im-'?
It could resolve any possible naming conflicts in the future, until we'll get possibility to rename compilation unit in sass. But appropriate task status at sass/sass is steel 'open', since 2012... :(

Throws $number` of `unit($number)` must be a number with gulp-sass

Trying to use it with Foundation 5 grids. While it works on codepen and sassmeister it throws the following error when compiling with gulp-sass. Am I doing something wrong? Would appreciate it if you could help.

gulp-sass] argument $number of unit($number) must be a number
Backtrace:
src/scss/quarks/_responsive.scss:226, in function unit
src/scss/quarks/_responsive.scss:226, in function get-expression-value
src/scss/quarks/_responsive.scss:264, in function parse-expression
src/scss/quarks/_responsive.scss:447, in mixin media
src/scss/quarks/_responsive.scss:449, in mixin media
src/scss/quarks/_responsive.scss:660 on line 226

Distribute this library via bower

I just finished reading your article on CSS-Tricks and think this would be a perfect candidate for distribution via Bower. Here are a few other (popular) repos I found on Bower that have the same goal, so we can probably use the same keywords in the bower.json file for maximum visibility on Bower:

It's a great library and I think it deserves the exposure!

Phone Landscape and Tablet

How can I write the following condition:
(> tablet) or (< tablet and landscape).

My intension is to not copy the same property when I need the same layout for Phone Landscape as in tablet.

v1.2 does not install via bower

Hi,

I've run this several times and I'm not getting version 1.2 to install. I checked what bower installed too, just to be sure and it is indeed installing 1.1.2 and not 1.2. Just to be sure, I also removed the package from my bower.json file and ran bower prune && bower cache clean so I'm pretty certain this isn't a cache issue.

screen shot 2015-05-30 at 12 38 57 pm

Automate build process

Couple of ideas:

  • Add a pre-commit hook to:
    • Run the tests
    • Run the linter
  • Add a Gulp build task
    • Update the dist
    • Update SassDoc

Nested media queries problem

This is not an issue of the library, it is sass in general, but would be nice if tackling this problem would be possible. The following code:

// ----
// libsass (v3.3.2)
// ----
@import "include-media";

@include media(">tablet", "<=desktop") {
  width: 50%;
  @include media(">phone") {
  width: 60%;
  }
  @include media(">tablet") {
  width: 70%;
  }
}

Produces this:

@media (min-width: 769px) and (max-width: 1024px) {
  width: 50%;
}

@media (min-width: 769px) and (max-width: 1024px) and (min-width: 321px) {
  width: 60%;
}

@media (min-width: 769px) and (max-width: 1024px) and (min-width: 769px) {
  width: 70%;
}

When the expected outcome would be:

@media (min-width: 769px) and (max-width: 1024px) {
  width: 50%;
}

/* 'and (min-width: 321px)' was left out as in not in a scope of parent */
@media (min-width: 769px) and (max-width: 1024px) {
  width: 60%;
}

/* 'and (min-width: 769px)' was left out as it duplicates already existing query */
@media (min-width: 769px) and (max-width: 1024px) {
  width: 70%;
}

If that can be achieved with another library as a additional step of post processing I will be grateful for suggestions.

Error in mapping

Hi there,
I 'bower-ed' @im and when I tried to compile the project with @im, I received this error:

Error in plugin 'gulp-ruby-sass'
Message:
error /izzui/bower_components/include-media/dist/_include-media.scss (Line 325: $map: (("palm" "screen and (max-width: 480px)"), ("lap" "screen and (min-width: 481px) and (max-width: 1023px)"), ("lap-and-up" "screen and (min-width: 481px)"), ("portable" "screen and (max-width: 1023px)"), ("desk" "screen and (min-width: 1024px)"), ("desk-wide" "screen and (min-width: 1280px)"), ("full-hd" "screen and (min-width: 1920px)"), ("retina" "(-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi)")) is not a map for `map-has-key')

Any idea?

Update documentation for declaration aliases

Is there any ability for declarations aliases. For example, I have a lot of phone only styles. I prefer to specify something like:

@include media("palm") { }

rather than:

@include media("<=phone") { }

Or for tablet only I want something like:

@include media("lap") { }

instead of:

@include media(">phone", "<=tablet") { }

Sure I can use mixins aliases:

@mixin lap {
    @include media(">phone", "<=tablet") {
        @content;
    }
}

div {
    @include lap {
        color: red;
    }
}

but it's not so flexible if I, for example, want add "retina" declaration for one particular rule.

Enhancement: Reduce bloat in output

Great mixin! It could introduce some sort of intelligence to reduce bloat in output.

The following example (with the default setup)

div {
  display: none;

  @include media(">=phone", "<tablet") {
    display: block;
  }
}

produces

div {
  display: none;
}
@media (min-width: 320px) and (max-width: 767px) {
  div {
    display: block;
  }
}

whereas phone is the first device in $breakpoints and more importantly with the smallest value on the range, and could as effectively be output as

div {
  display: none;
}
@media (max-width: 767px) {
  div {
    display: block;
  }
}

The same principle can be applied at the upper end of the range.

EDIT: To further explain the benefit: it doesn't make sense applying a media query to smallest and largest denominators. We're not capping our styles with (max-width: 8000px), why would we limit them to (min-width: 320px).

sass doesn't compile when using media query ranges

I'm using grunt to compile my sass on a 10.10.3 iMac.

These statements cause grunt to eat all the available memory, and lock the machine (eventually):

@include media (">tablet" , "<desktop") { ... }

These are my breakpoints:
$breakpoints: (
'phone': 320px,
'tablet': 768px,
'desktop': 1024px
) !default;

Problem compiling with latest node-sass when using multiple rules

Compilation doesn't finish and all RAM is consumed in the process, when using multiple rules (that includes using $media-expressions)

minimal example.scss:

@import 'bower_components/include-media/dist/include-media';

@include media( ">20rem", "<40rem" ) { 
    body{
        color: blue;
    }   
}

I've tested it and the problem happens with include-media versions 1.2, 1.1.2 and 1.0.0.

In Ubuntu 14.04, using node.js 10.38 and these versions of node-sass (libsass):

  • node-sass 3.1.1 (libsass 3.2.4)
  • node-sass 3.0.0 (libsass 3.2.2),

But it compiles succesfully with:

  • node-sass 2.1.1 (libsass 3.1.0)

Steps to reproduce:

npm install [email protected]
bower install include-media#1.1.2

./node_modules/.bin/node-sass example.scss

(To see the available versions: npm info node-sass)

I'm sending the bugreport here, but upon confirmation I believe it'd be better if you be the one who sends the report to either library, or both.

EDIT I've realized this happens when using multiple arguments, not justs media-expressions

Rewrite the _parse-expression function

/// Get operator of an expression
/// @param {String} $expression - Expression to extract operator from
/// @return {String} - Any of `>=`, `>`, `<=`, `<`, `≥`, `≤`
@function get-expression-operator($expression) {
  @each $operator in ('>=', '>', '<=', '<', '', '') {
    @if str-index($expression, $operator) {
      @return $operator;
    }
  }

  @error 'No operator found in `#{$expression}`.';
}

/// Get dimension of an expression, based on a found operator
/// @param {String} $expression - Expression to extract dimension from
/// @param {String} $operator - Operator from `$expression`
/// @return {String} - `width` or `height` (or potentially anything else)
@function get-expression-dimension($expression, $operator) {
  $operator-index: str-index($expression, $operator);
  $dimension: str-slice($expression, 0, $operator-index - 1);

  @return if(str-length($dimension) == 0, 'width', $dimension);
}

/// Get dimension prefix based on an operator
/// @param {String} $operator - Operator
/// @return {String} - `min` or `max`
@function get-expression-prefix($operator) {
  @return if(index(('<', '<=', ''), $operator), 'max', 'min');
}

/// Get value of an expression, based on a found operator
/// @param {String} $expression - Expression to extract value from
/// @param {String} $operator - Operator from `$expression`
/// @return {Number} - A numeric value 
@function get-expression-value($expression, $operator) {
  $operator-index: str-index($expression, $operator);
  $value: str-slice($expression, $operator-index + str-length($operator));

  @if map-has-key($breakpoints, $value) {
    $value: map-get($breakpoints, $value);
  } @else if map-has-key($media-expressions, $value) {
    $value: map-get($media-expressions, $value);
  } @else {
    $value: to-number($value);
  }

  $interval: map-get($unit-intervals, unit($value));

  @if not $interval {
    @error 'Unknown unit `#{unit($value)}`.';
  }

  @if $operator == '>' {
    $value: $value + $interval;
  } @else if $operator == '<' {
    $value: $value - $interval;
  }

  @return $value;
}

/// Parse an expression to return a valid media-query expression
/// @param {String} $expression - Expression to parse
/// @return {String} - Valid media query
@function parse-expression($expression) {
  $operator: get-expression-operator($expression);
  $dimension: get-expression-dimension($expression, $operator);
  $prefix: get-expression-prefix($operator);
  $value: get-expression-value($expression, $operator);

  @return '(#{$prefix}-#{$dimension}: #{$value})'
}

Relevant SassMeister: http://sassmeister.com/gist/31d4b8c5d88c6deadb1e.

Functions not recognised in webstorm

I have the latest version of SASS compiler installed (3.4.21). I applied "_include-media.scss" to my project. I use Webstorm IDE (Latest version 11.0.3 and I find several functions are not recognised and as a consequence SASS fails to compile.

  noop(), 
  get-expression-operator($condition);
  get-expression-prefix($operator);
  get-expression-value($condition, $operator);
  to-number($value);

above functions not recognised,

Line 441 - unexpected token:

@return if($minus, -$result, $result);; - obvious two semi-colons.

@include media(slice($conditions, 2)...) { - invalid argument

Shame as this appears to offer very useful functionality.

Namespacing

I just tried to implement this library while also using Neat. Unfortunately both libraries define @mixin media(), which results in incompatibility.

Is there a chance that you might namespace all provided mixins/functions with `ìm-``? This is already done with most components of this library, but some are not namespaced. This would make it much easier to combine your library with others.

Thanx a lot!

Loop through breakpoints and generate media queries.

Hi Guys, I'm trying to simplify a bit code I have... and largely this works very well but I'm a bit new to Sass so I'm probably just missing something here.

I have a set of .hidden rules for, from and up to certain breakpoints. The --from and --upto parts work, but getting it to work between breakpoints is slightly more difficult.

.hidden{
    @include hidden;
}

@each $breakpoint in $all-breakpoints {
    $breakpoint-name: nth($breakpoint, 1);
    $upto-breakpoint: 'Unsure what Sass is needed here';


    @include media('>=#{$breakpoint-name}', '<#{$upto-breakpoint}'){
        .hidden--for-#{$breakpoint-name}{
            @include hidden();
        }
    }

    @include media('>=#{$breakpoint-name}'){
        .hidden--from-#{$breakpoint-name}{
            @include hidden();
        }
    }

    @include media('<#{$breakpoint-name}'){
        .hidden--upto-#{$breakpoint-name}{
            @include hidden();
        }
    }
}

To get this to work, I kinda need to populate the $upto-breakpoint var with the next breakpoint so It has minimum and maximum values. Ive tried a couple of different things but nothing has worked. Any help appreciated!

Libsass support?

Currently getting this when trying to compile:

stylesheets/vendor/include-media:17: error: error reading values after phone

I realise this is because Libsass doesn't support list maps - any work around for this? I've got quite used to my Sass compiling near enough instantly :)

Charset error, invalid character

As the main SCSS file (include-media/dist/_include-media.scss) uses and chars, there's the following error arising:

Invalid US-ASCII character "\xE2"

Please add @charset "UTF-8"; as first line in those files to avoid such errors with SCSS.

Thanks in advance!

Add a CONTRIBUTING.md

Specifying:

  • Code should stick to Sass Guidelines
  • Sass items should be documented with SassDoc
  • Tests should pass
  • Simplicity is priority

include index.js to help with creating includePaths?

Something like https://github.com/ranjandatta/node-normalize-scss/blob/master/index.js

This would allow us to easily add include-media to the Sass includePath without needing to reach into the node_modules directory.


I was able to get this working, but I had to use the following code:

@import "../node_modules/include-media/dist/include-media";

$hidpi: "retina2x";

#foo {
  @include media($hidpi) {
    content: 'Device Pixel Ratio of at least 1.5';
  }
}

Output mobile first media queries by default

If no operator is specified with a breakpoint key an error gets thrown. Would it be possible to fall back to a min-width media query (>= operator) if one of the keys in $breakpoints is used without an operator?

That would be very convenient since that type of media query is probably used most of the time.

Input:

@include media(phone) {
    width: 50%;
}

Desired output:

@media (min-width: 320px) {
    width: 50%;
}

What about vertical responsive behavior?

First of all, this is a very cool thing, thank you guys for it.
But don't forget about vertical responsive behavior. I mean queries with max-height and min-height. It is very important for devices with extra-wide and short(height) screens.
So, please add some functions to handle this problem.
@include media("^700px") {
some code
}

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.