Send properties as argument for mixin - css

I'd like to break out all of my Media-queries and pass the CSS properties as arguments instead.
.bp1(#css){
#media (max-width: 959px){
#css
}
}
.bp1(width: 186px;);
Unfortunately, this wont work and makes the Less fail :(

Starting with Less v1.7.0, it is possible to pass detached rulesets as parameter to a mixin.
Quoting Less Website:
Detached ruleset is a group of CSS properties, nested rulesets, media declarations or anything else stored in a variable. You can include it into a ruleset or another structure and all its properties are going to be copied there. You can also use it as a mixin argument and pass it around as any other variable.
Note that the properties that form a part of the ruleset must be enclosed within {}. Also, parentheses (()) are a must after the detached ruleset call (like #css();). Without the parentheses at the end, the call would not work.
.bp1(#css){
#media (max-width: 959px){
div{
#css(); // detached ruleset call
}
}
}
.bp1({width: 186px;}); // passing ruleset to mixin
Compiled Output:
#media (max-width: 959px) {
div {
width: 186px;
}
}
Alternately, the ruleset can be assigned to a variable which in-turn can be passed in the mixin call like below. This would also produce the same output when compiled.
.bp1(#css){
#media (max-width: 959px){
div{
#css(); // detached ruleset call
}
}
}
#ruleset: {width: 186px;};
.bp1(#ruleset);
Using this feature, it is possible to pass not only group of properties but also the selectors along with it (like shown below):
.bp1(#css){
#media (max-width: 959px){
#css(); // detached ruleset call
}
}
.bp1({
div{width: 186px;}
div#header{color: gold;}
});
Compiled Output:
#media (max-width: 959px) {
div {
width: 186px;
}
div#header {
color: gold;
}
}

The LESS documentation about mixins says: "Mixins allow you to embed all the properties of a class into another class by simply including the class name as one of its properties. It’s just like variables, but for whole classes. Mixins can also behave like functions, and take arguments, as seen in the example bellow."
You can't have anything but css properties and their values, either stated or represented by a variable, in a mixin. So what you're trying to do is invalid.

Related

pass global value css in #media [duplicate]

I am trying to use CSS variables in media query and it does not work.
:root {
--mobile-breakpoint: 642px;
}
#media (max-width: var(--mobile-breakpoint)) {
}
From the spec,
The var() function can be used in place of any part of a value in
any property on an element. The var() function can not be used as
property names, selectors, or anything else besides property values.
(Doing so usually produces invalid syntax, or else a value whose
meaning has no connection to the variable.)
So no, you can't use it in a media query.
And that makes sense. Because you can set --mobile-breakpoint e.g. to :root, that is, the <html> element, and from there be inherited to other elements. But a media query is not an element, it does not inherit from <html>, so it can't work.
This is not what CSS variables are trying to accomplish. You can use a CSS preprocessor instead.
As Oriol has answered, CSS Variables Level 1’s var() cannot currently be used in media queries. However, there have been recent developments that will address this problem. Once CSS Environment Variables Module Level 1 is standardized and implemented, we’ll be able to use env() variables in media queries in all modern browsers.
The CSS Working Group (CSSWG) codified env() in a new standard (currently at a draft stage): the CSS Environment Variables Module Level 1 (see this GitHub comment and this comment for more info). The draft calls out variables in media queries as an explicit use case:
Because environment variables don’t depend on the value of anything drawn from a particular element, they can be used in places where there is no obvious element to draw from, such as in #media rules, where the var() function would not be valid.
If you read the specification and have a concern, or if you want to voice your support for the media-query use case, you can do so in issue #2627, in issue #3578, or in any CSS GitHub issue labeled with “css-env-1”.
GitHub issue #2627 and GitHub issue #3578 are devoted to custom environmental variables in media queries.
Original answer from 2017-11-09:
Recently, the CSS Working Group decided that CSS Variables Level 2 will support user-defined environment variables using env(), and they will try to make them be valid in media queries. The Group resolved this after Apple first proposed standard user-agent properties, shortly before the official announcement of iPhone X in September 2017 (see also WebKit: “Designing Websites for iPhone X” by Timothy Horton). Other browser representatives then agreed they would be generally useful across many devices, such as television displays and ink printing with bleed edges. (env() used to be called constant(), but that has now been deprecated. You might still see articles that refer to the old name, such as this article by Peter-Paul Koch.) After some weeks passed, Cameron McCormack of Mozilla realized that these environment variables would be usable in media queries, and Tab Atkins, Jr. of Google then realized that user-defined environment variables would be especially useful as global, non-overridable root variables usable in media queries. Now, Dean “Dino” Jackson of Apple will join Atkins in editing Level 2.
You can subscribe to updates on this matter in w3c/csswg-drafts GitHub issue #1693 (for especially relevant historical details, expand the meeting logs embedded in the CSSWG Meeting Bot’s resolutions and search for “MQ”, which stands for “media queries”).
What you can do however is #media query your :root statement!
:root {
/* desktop vars */
}
#media screen and (max-width: 479px) {
:root {
/* mobile vars */
}
}
Totally works in Chrome, Firefox and Edge at least the latest production versions as of this posting.
One limitation: if you need to access the value as a variable – for example to use in calculations elsewhere – you will need to have a variable, and it requires defining the variable in two places: the media query and variable declaration.
Apparently it's just not possible to use native CSS variables like that. It's one of the limitations.
A clever way to use it is to change your variables in the media-query, to impact all your style. I recommend this article.
:root {
--gutter: 4px;
}
section {
margin: var(--gutter);
}
#media (min-width: 600px) {
:root {
--gutter: 16px;
}
}
One way to achieve what you want is using npm package postcss-media-variables.
If you are fine with using npm packages then you can take a look documentation for same here:
postcss-media-variables
Example
/* input */
:root {
--min-width: 1000px;
--smallscreen: 480px;
}
#media (min-width: var(--min-width)) {}
#media (max-width: calc(var(--min-width) - 1px)) {}
#custom-media --small-device (max-width: var(--smallscreen));
#media (--small-device) {}
The level 5 specification of media queries define Custom Media Queries that does almost what you are looking for. It allows you to define breakpoint similar to how you do with CSS variables and later use them in different places.
Example from the specification:
#custom-media --narrow-window (max-width: 30em);
#media (--narrow-window) {
/* narrow window styles */
}
#media (--narrow-window) and (script) {
/* special styles for when script is allowed */
}
There is still no support for this actually so we have to wait before using this feature.
Short Answer
You can use JavaScript to change the value of media queries and set it to the value of a css variable.
// get value of css variable
getComputedStyle(document.documentElement).getPropertyValue('--mobile-breakpoint'); // '642px'
// search for media rule
var mediaRule = document.styleSheets[i].cssRules[j];
// update media rule
mediaRule.media.mediaText = '..'
Long Answer
I wrote a small script which you can include on your page. It replaces every media rule with a value of 1px with the value of the css variable --replace-media-1px, rules with value 2px with --replace-media-2px and so on. This works for the media queries with, min-width, max-width, height, min-height and max-height even when they are connected using and.
JavaScript:
function* visitCssRule(cssRule) {
// visit imported stylesheet
if (cssRule.type == cssRule.IMPORT_RULE)
yield* visitStyleSheet(cssRule.styleSheet);
// yield media rule
if (cssRule.type == cssRule.MEDIA_RULE)
yield cssRule;
}
function* visitStyleSheet(styleSheet) {
try {
// visit every rule in the stylesheet
var cssRules = styleSheet.cssRules;
for (var i = 0, cssRule; cssRule = cssRules[i]; i++)
yield* visitCssRule(cssRule);
} catch (ignored) {}
}
function* findAllMediaRules() {
// visit all stylesheets
var styleSheets = document.styleSheets;
for (var i = 0, styleSheet; styleSheet = styleSheets[i]; i++)
yield* visitStyleSheet(styleSheet);
}
// collect all media rules
const mediaRules = Array.from(findAllMediaRules());
// read replacement values
var style = getComputedStyle(document.documentElement);
var replacements = [];
for (var k = 1, value; value = style.getPropertyValue('--replace-media-' + k + 'px'); k++)
replacements.push(value);
// update media rules
for (var i = 0, mediaRule; mediaRule = mediaRules[i]; i++) {
for (var k = 0; k < replacements.length; k++) {
var regex = RegExp('\\((width|min-width|max-width|height|min-height|max-height): ' + (k+1) + 'px\\)', 'g');
var replacement = '($1: ' + replacements[k] + ')';
mediaRule.media.mediaText = mediaRule.media.mediaText.replace(regex, replacement);
}
}
CSS:
:root {
--mobile-breakpoint: 642px;
--replace-media-1px: var(--mobile-breakpoint);
--replace-media-2px: ...;
}
#media (max-width: 1px) { /* replaced by 642px */
...
}
#media (max-width: 2px) {
...
}
You can build a media query programmatically using matchMedia:
const mobile_breakpoint = "642px";
const media_query = window.matchMedia(`(max-width: ${mobile_breakpoint})`);
function toggle_mobile (e) {
if (e.matches) {
document.body.classList.add("mobile");
} else {
document.body.classList.remove("mobile");
}
}
// call the function immediately to set the initial value:
toggle_mobile(media_query);
// watch for changes to update the value:
media_query.addEventListener("change", toggle_mobile);
Then, instead of using a media query in your CSS file, apply the desired rules when body has the mobile class:
.my-div {
/* large screen rules */
}
.mobile .my-div {
/* mobile screen rules */
}
As you can read other answers, still not possible to do so.
Someone mentioned custom environmental variables (similar to custom css variables env() instead of var()), and the principle is sound, though there are still 2 major issues:
weak browser support
so far there is no way to define them (but probably will be in the future, as this is so far only an unofficial draft)

Can I use mixins to generate new mixins in LESS?

I'm trying to use LESS to dynamically generate a set of mixins that would help me write cleaner media query code. So far in my limited knowledge of the language I've put together code that looks like this:
#sizes: xxs, xs, sm, md, lg;
.mediaQueries(#iterator:1) when(#iterator <= length(#sizes)) {
//Extract name
#sizeName: extract(#sizes, #iterator);
//Attempt to build min-width query
.MQ-min-#{sizeName} (#content) {
#media (min-width: #screen-#{sizeName}) {
#content();
}
}
//Attempt to build max-width query
.MQ-max-#{sizeName} (#content) {
#media (max-width: #screen-#{sizeName}) {
#content();
}
}
.mediaQueries((#iterator + 1));
}
.mediaQueries();
The goal is to have a set of mixins that would allow me to easily and cleanly define some CSS properties for a specific breakpoint, like so:
.generic-class {
background: black;
//Sizes #screen-sm and up
.MQ-min-sm({
background: transparent;
})
}
It doesn't work. Something to note, I'm trying to interpolate the size name into a variable name that would then output me a the px value of that variable into the #media query. Is something like this even possible?
Otherwise my compiler currently breaks on the start of the nested mixin (.MQ-min-#{sizeName} (#content) {) with the error:
Potentially unhandled rejection [2] Missing closing ')' in file ../mixins.less line no. 43
Is something like what I'm trying to achieve possible?
I think the simplest way for you to achieve this is by using a single parametric mixin like given below. This avoids the need for all those iterations, dynamic mixin creations etc.
#sizes: xxs, xs, sm, md, lg;
#screen-xxs: 100px;
#screen-sm: 200px;
.MQ(#content, #sizeName, #max-min) { /* get ruleset, size name and min/max as input */
#selector: ~"(#{max-min}-width: #{screen-#{sizeName}})"; /* form the media selector */
#media #selector { /* use it */
#content();
}
}
.generic-class {
background: black;
.MQ({
background: transparent;
}, /* ruleset */
sm, /* screen size */
max /* min/max */
);
}
If the mixins are for your own usage then this is all that you need. If it is for distribution as library then you may want to put some guards on #sizeName and #max-min variables to restrict invalid values.
Note: Less compiler always had a problem with the interpolation here - #media (min-width: #screen-#{sizeName}) also (I am not sure if it has been addressed) and that's why I created a temp variable.

What is the purpose of including "all" in #media rules?

So you see a lot of code examples do something like
#media all and (max-width:640px) {
div {
background-color:red;
}
}
Now afaik, the keywords "all" and "screen" and some others are for selecting the device type this applies to and the line is just supposed to provide a boolean output.
Since "all" applies to every device, one would imagine that its always 1 and (1 && x) always equals x so "all and" should make no difference whatsoever.
I tried out
#media (max-width:640px) {
div {
background-color:red;
}
}
and at least my browsers agree. Is there anything else I should know about?
See the spec: https://www.w3.org/TR/css3-mediaqueries/
The ‘print’ and ‘screen’ media types are defined in HTML4. The complete list of media types in HTML4 is: ‘aural’, ‘braille’, ‘handheld’, ‘print’, ‘projection’, ‘screen’, ‘tty’, ‘tv’. CSS2 defines the same list, deprecates ‘aural’ and adds ‘embossed’ and ‘speech’. Also, ‘all’ is used to indicate that the style sheet applies to all media types.
...
A shorthand syntax is offered for media queries that apply to all media types; the keyword ‘all’ can be left out (along with the trailing ‘and’). I.e. if the media type is not explicitly given it is ‘all’.
/* I.e. these are identical: */
#media all and (min-width:500px) { … }
#media (min-width:500px) { … }
/* As are these: */
#media (orientation: portrait) { … }
#media all and (orientation: portrait) { … }
In addition, the following media types: 'tty', 'tv', 'projection', 'handheld', 'braille', 'embossed', 'aural' have been deprecated in Media Queries Level 4.
all refers to: all media type devices, print: used for printing, screen: used for desktop screens, mobiles, tablets etc and speech: used for screen-readers that "reads" the page out loud.
In your case where you have specified media type as all, you can try printing the page by right clicking. The printed page will have all the styles applied in short it will exactly look the same.
Now take another example where you specify the media type as screen. If you try to print the page you will not see all the styles getting applied to the page as the styles were defined for screen alone.
If one does not specify all in media query it is by default taken as all.
#media screen {
div {
color: blue;
}
.print{
display: none;
}
}
#media print and (min-width: 200px){
div{
color: tomato;
}
div.not('.example'){
display:none !important;
}
.print{
display: block;
}
}
<div class="example">
<div>Try printing me. See if this blue color appears while printing</div>
<div class="print">I am only visible while printing.</div>
</div>

Is it possible to use Foundation semantic grid mixins inside mediaqueries?

I've made a small example grid with the foundation framework(http://foundation.zurb.com/). The grid is made out of four floating elements on a desktop mode(_setting, $rowWidth 1140px)
*markup
<div id="container">
<div id="main">
<div id="column">
*scss
#container{
#include outerRow();
}
.column{
#include column(3);
}
Above mixins based on these sources: http://foundation.zurb.com/docs/sass-mixins.php
Now I want to change the column structure when the example will be viewed on a tablet in portrait mode. I've made something like this:
#media screen and (min-width: 768px) and (orientation: portrait) {
#container{
#include outerRow();
}
.column{
#include column(6);
}
}
The following error occurs:
> DEPRECATION WARNING on line 21 of /Library/Ruby/Gems/1.8/gems/zurb-foundation-3.2.3/scss/foundation/mixins/_semantic-grid.scss:
> #extending an outer selector from within #media is deprecated.
> You may only #extend selectors within the same directive.
> This will be an error in Sass 3.3.
> It can only work once #extend is supported natively in the browser.
Can anybody tell me what the working method is to re-define the column structure for each different media query in a foundation based project?
Generally speaking, all you should need to do is redefine the extend mixins like %clearfix within your media query. If those classes are defined within another file, importing the file would also work (provided you aren't placing it within some sort of control block, like an if/else statement).
Looking at the source of the project, what you're looking to do probably shouldn't be done that way (see: https://github.com/zurb/foundation/blob/master/scss/foundation/mixins/_semantic-grid.scss)
Both of the mixins referenced in your sample code generate their own media queries, so avoid invoking them twice on the same element or you'll end up with a lot of duplicate/unused CSS. Instead, just overwrite the properties that actually need modifying:
.exampleA {
#include outerRow();
#media screen and (min-width: 768px) and (orientation: portrait) {
// do not #include outerRow() again here!
// these are the only properties that are variable in the outerRow() mixin:
width: $tabletWidth;
min-width: $tabletMinWidth;
}
}
The other thing you need to realize is that once you've defined your $totalColumns, you're stuck with it when using the column mixin (see: https://github.com/zurb/foundation/blob/master/scss/foundation/mixins/_semantic-grid.scss#L64 and https://github.com/zurb/foundation/blob/master/scss/foundation/mixins/_semantic-grid.scss#L19). You can't have 6 total columns by default and then 4 for your tablet. If you need to be able to this, you could simply run the gridCalc() function yourself:
.exampleB {
#include column(6);
#media screen and (min-width: 768px) and (orientation: portrait) {
width: gridCalc(2, 6); // columns, totalColumns
}
}
If you're ok with the number of $totalColumns for your media query, pass $totalColumns as the 2nd argument.

SASS 3.2 Media Queries and Internet Explorer Support

I recently implemented this technique with SASS 3.2 using #content blocks on a project I've been working on, and I've just gotten to the point where I need to include support for older browsers such as IE7 and 8.
Example:
.overview {
padding: 0 0 19px;
#include respond-to(medium-screens) {
padding-top: 19px;
} //medium-screens
#include respond-to(wide-screens) {
padding-top: 19px;
} //medium-screens
}
They both don't support media queries, and I've often handled this in the past by serving up all styles to these browsers when I had my media queries separated into separate partial files such as _320.scss, _480.scss and in my IE stylesheet loading them like so:
#import 320.scss;
#import 480.scss;
etc.
Which would load all styles, and always assign IE7 - 8 a 940px (or whatever the max width is) layout and styles. By nesting styles in SASS 3.2 inline like this, it eliminates the need for separate partial stylesheets, but totally screws up how I load styles for IE.
Any ideas or solutions on how to combat this? I could use a polyfill such as respond.js to force IE to use media queries, but would prefer to just serve up a non-flexible site to IE.
Any ideas on either how to best organize these files, or a better solution?
You can generate a separate stylesheet for IE<9 that contains everything your normal sheet has, but with flattened media queries based on a set width.
Full explanation here http://jakearchibald.github.com/sass-ie/, but basically you have this mixin:
$fix-mqs: false !default;
#mixin respond-min($width) {
// If we're outputting for a fixed media query set...
#if $fix-mqs {
// ...and if we should apply these rules...
#if $fix-mqs >= $width {
// ...output the content the user gave us.
#content;
}
}
#else {
// Otherwise, output it using a regular media query
#media screen and (min-width: $width) {
#content;
}
}
}
Which you'd use like this:
#include respond-min(45em) {
float: left;
width: 70%;
}
This would be inside all.scss, which would compile down to all.css with media queries. However, you'd also have an additional file, all-old-ie.scss:
$fix-mqs: 65em;
#import 'all';
That simply imports all, but flattens media query blocks given a fake width of 65em.
I use LESS for a lot of my work, but on larger projects, with many people working across files, I don't like using breakpoint files, such as 1024.less.
My and my team use a modular approach, such as header.less which contains all the code for just the header, including the associated breakpoints.
To get round IE problems (we work in a corporate environment), I use this approach:
#media screen\9, screen and (min-width: 40em) {
/* Media queries here */
}
The code inside the media query is always executed by IE7 and less. IE9 and above obeys the media queries like a proper browser should. The problem is IE8. To solve this, you need to make it behave like IE7
X-UA-Compatible "IE=7,IE=9,IE=edge"
I've found this doesn't always work if set in the metatags in the HTML, so set it using the server headers.
See the gist here:
https://gist.github.com/thefella/9888963
Making IE8 act like IE7 isn't a solution that works for everyone, but it suits my needs.
Jake Archibald has the best technique I've seen to date for achieving this. This technique automatically creates a separate stylesheet for IE, with all the same styles inside of your media queries but without the media query itself.
I also campaigned to get this technique built into the popular breakpoint extension for Sass, if you're interested in using that!
If you wanted to keep everything under one roof and only have a single http request for your older browser visitors you could do something like this
Setting up your initial respondto mixin
// initial variables set-up
$doc-font-size: 16;
$doc-line-height: 24;
// media query mixin (min-width only)
#mixin breakpoint($point) {
#media (min-width: $point / $doc-font-size +em) { #content; }
}
this will create a min-width media query and output your px value ($point) as an em value.
From this you'd need to create this mixin
#mixin rwdIE($name, $wrapper-class, $IE: true) {
#if $IE == true {
.lt-ie9 .#{$wrapper-class} {
#content;
}
.#{$wrapper-class} {
#include breakpoint($name) {
#content;
}
}
}
#else if $IE == false {
.#{$wrapper-class} {
#include breakpoint($name) {
#content;
}
}
}
}
Here if you pass a piece of Sass(SCSS) like this
#include rwdIE(456, test) {
background-color: #d13400;
}
it will return this code
.lt-ie9 .test {
background-color: #d13400;
}
#media (min-width: 28.5em) {
.test {
background-color: #d13400;
}
}
This will give you the you the IE and 'new browser' CSS in one file. If you write -
#include rwdIE(456, test, false) {
background-color: #d13400;
}
You will get -
#media (min-width: 28.5em) {
.test {
background-color: #d13400;
}
}
I hope this helps, I've got this on a codepen here too - http://codepen.io/sturobson/pen/CzGuI
There is a CSS3 Mixin I use that has a variable for IE filters. You could do something similar by having a global variable, $forIE or something, wrap the media query mixin within an if and then generate the stylesheet with or w/o the queries.
#if $forIE == 0 {
// Media Query Mixin
}
Or use the #if to import a 3rd scss (_forIE.scss?) that will override things with your IE specific styles.

Resources