A completely different way to write responsive, vanilla, CSS

栏目: IT技术 · 发布时间: 4年前

Basics of css-media-vars

css-media-vars adds several --custom-css-variables, all namespaced with "--media-" and based on media queries, onto the HTML tag. These vars act as universal mixins for your CSS values. If the media query is true, your value will be used. If it's false, the var(..., fallback) will be used.

For example, there are several named breakpoints that respond to the width of the screen, such as --media-lte-sm .

In your CSS, if you want a value to only apply when the screen is less than or equal to the "small" breakpoint range, you mix it into your value:

--my-small-value: var(--media-lte-sm) 2px;

From this point, you can use your variable anywhere and it will only be "2px" if the media query is true. Else, it uses the fallback you provide, like so:

border: var(--my-small-value, 15px) solid green;
A completely different way to write responsive, vanilla, CSS

Here's a link to the jsbin pictured in the gif: https://jsbin.com/giqedowale/edit?css,output

If you need multiple break points, all you have to do is mix a different breakpoint into another variable and use it in the first fallback:

          --my-small-value: var(--media-lte-sm) 2px;

          --my-medium-value: var(--media-md) 15px;

          border: var(--my-small-value, var(--my-medium-value, 30px)) solid green;

        

In this case, because the small values are listed first, this approach is mobile-first ! CSS Variables don't compile the fallback unless it's used (similar to the expected short-circuting of conditionals in JavaScript).

This is all vanilla CSS. No JS or build step is necessary.

The library is small and built on a CSS trick called "Space Toggle" discovered in the development of augmented-ui . You can read more about Space Toggle in these tweets which contain links to JSBins you can explore further with:

Second Tweet, a simple demo

First Tweet, an advanced demo

Browser support for CSS Variables is currently 94% globally according to caniuse .

Each of the --media-* vars are using the actual media query in CSS to switch them to the "true" state. Browser support depends on the feature but will always behave as if it's "false" if the media query isn't supported in the user's browser, such as --media-prefers-light which only recently gained traction.


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

另一个地球

另一个地球

[美]马克·格雷厄姆、威廉·H·达顿 / 胡泳、徐嫩羽 / 电子工业出版社 / 2015-10-1 / 78

互联网在日常工作和生活中扮演日益重要的角色,互联网将如何重塑社会?本书通过汇集有关互联网文化、经济、政治角色等问题的研究成果,提供了特定社会制度背景下解决这一问题的根本办法。 关于互联网的研究是蓬勃发展的崭新领域,牛津大学互联网研究院(OII)作为创新型的跨学科学院,自成立起就专注于互联网研究。牛津大学互联网研究院关于互联网+社会的系列讲座在一定程度上塑造了互联网+社会。本书内容基于不同学科......一起来看看 《另一个地球》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具