且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

CSS3媒体查询放在哪里?

更新时间:2022-12-16 08:13:44

方法2 对我来说效果更好.

当我是新手时,我正在使用方法1 -我正在一起编写媒体查询(在样式表的底部或在另一个文件中).

When I was a newbie, I was using Approach #1 - I was writing my media queries together (at the bottom of my stylesheet or in another file).

.header { ... }
.news-item { ... }
.footer { ... }

/**
 * ...
 *
 * bla bla, imagine a huge amount of styles here
 *
 * ...
 */

/** All style tweaks for screens < 1024px */
@media screen and (max-width: 1024px) {
  .header { ... }
  .news-item { ... }
}

此方法有一些缺点.根据我的经验,最值得注意的是可维护性很困难.主要原因是:.news-item逻辑分布在CSS的多行无关的地方.

This approach has a few downsides. Based on my experience, the most notable one is that the maintainability is a hard. The main reason: .news-item logic is spread across multiple unrelated lines of CSS.

后来,我自然决定将相关样式保持在一起. 方法2 :

Later on, naturally, I decided to keep the related styles together. Approach #2:

/** Header's styles and media queries */
.header {
  ...
}
@media screen and (max-width: 1024px) {
  .header { ... }
}
@media screen and (max-width: 720px) {
  .header { ... }
}

/** News-item's styles and media queries */
.news-item {
  ...
}
@media screen and (max-width: 1024px) {
  .news-item { ... }
}
@media screen and (max-width: 720px) {
  .news-item { ... }
}

/** ... and so on */

但是,在这种方法中,全方位重复媒体查询max-width值看起来不够可维护.我通过使用CSS预处理器(如SASS)解决了这个问题,该预处理器使我可以将所有变量替换为变量并对其进行一次定义.

However, in this approach, repeating media queries max-width values all-around doesn’t look maintainable enough. I solved this issue by using a CSS pre-processor (like SASS) that allows me to replace all them with variables and define them once.

为了提高可维护性并使这些定义更加优雅,我开始在Media Queries之上使用抽象.

To boost up the maintainability and to make these definitions a lot more elegant I started to use an abstraction on top of the Media Queries.

如果您对更多详细信息感兴趣,请在我的博客文章中阅读:-)

If you're interested in more details, please read on my blog post :-)