Currently, I am using LESS as my main CSS pre-processor. I have (and I am sure a lot of people have this need) to define variables in a @media
query like:
@media screen and (max-width: 479px) {
myVar: 10px;
}
@media screen and (min-width: 480px) and (max-width: 767px) {
myVar: 20px;
}
@media screen and (min-width: 768px) {
myVar: 30px;
}
.myElement {
padding: @myVar;
}
This doesn't work in LESS, because of the compiling nature (@myVar
is defined within a scope of each particular @media
only, but not globally). Even if I define @myVar
globally before the media queries, it is not updated in accordance to the media queries and .myElement
gets that initial value no matter what.
So, the question is, is it possible to achieve this in any other CSS pre-processor, or we are doomed to override the .myElement
within each media query? Not a problem in this simplest example, but in real projects this could save a lot of time and copy/pasting.
EDIT:
Not a solution, but a workaround for my particular project:
- Set font-size on
<html>
to base font-size
myVar
LESS variable is defined in rem
instead of px
as a derivative of the base font-size
- Use
@media
queries to adjust base font-size for different media.
- OPTIONAL Use REM unit polyfill for browsers, that don't yet support
rem
(http://caniuse.com/#search=rem). This will not work in IE 8 and below, but not because of lack of support for rem
– it doesn't support media queries. So IE8 and below get full-size media-queries-free stylesheet anyway.
Code snippet:
@myVar: .77rem; // roughly 10px, 20px and 30px respectively
html { font-size: 13px }
@media screen and (min-width: 480px) and (max-width: 767px) {
html { font-size: 26px }
}
@media screen and (min-width: 768px) {
html { font-size: 39px }
}
.myElement {
padding: @myVar;
}
Here is a JSBin with more extensive example that mixes different font-size elements with differently measured blocks.
Easy and flexible for my needs. Hopefully will be helpful for somebody else.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…