How to use > or < (Greater than and Less than )

2019-03-18 00:42发布

问题:

Can we use the ">" or "<" symbols(Greater than and Less than ) in media queries? for example I would like to hide a dive for all monitors less than 768px. can I say some thing like this:

@media screen and (min-width<=768px) {}

回答1:

Media queries don't make use of those symbols. Instead, they use the min- and max- prefixes. This is covered in the spec:

  • Most media features accept optional ‘min-’ or ‘max-’ prefixes to express "greater or equal to" and "smaller or equal to" constraints. This syntax is used to avoid "<" and ">" characters which may conflict with HTML and XML. Those media features that accept prefixes will most often be used with prefixes, but can also be used alone.

So, instead of something like (width <= 768px), you would say (max-width: 768px) instead:

@media screen and (max-width: 768px) {}


回答2:

@media screen and (max-width: 768px) { ... }


回答3:

Check out the Sass lib include-media, which (despite being for Sass) explains how calls like @include media('<=768px') maps to plain CSS @media queries. In particular, see this section of the docs.

TLDR, what you learn from there is:

To do the equivalent of something like media('<=768px') (less than or equal to 768) in CSS, you need to write

@media (max-width: 768px) {}

and to do the equivalent of media('<768px') (less than 768) in CSS, you need to write

@media (max-width: 767px) {}

Notice how I subtracted 1 from 768, so that the max width is less than 768 (because we wanted to emulate the < less-than behavior which doesn't actually exist in CSS).

So to emulate something like media('>768px', '<=1024') in CSS, we would write:

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

and media('>=768px', '<1024') would be

@media (min-width: 768px) and (max-width: 1023px) {}