CSS3媒体查询放在哪里? [英] Where to put CSS3 media queries?

查看:557
本文介绍了CSS3媒体查询放在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与自己进行哲学辩论,讨论将媒体查询放入样式表的最佳位置.我正在尝试以模块化方式构造CSS(例如OOCSS或SMACSS等).在这种情况下,我看到两个选择:

I am having a philosophical debate with myself over the best place to put media queries within style sheets. I am attempting to structure my CSS modularly (like OOCSS or SMACSS, etc). Given that context, I see two choices:

  1. 将所有媒体查询放在单独的样式表或主样式表的一部分中.
  2. 将媒体查询置于其基本副本下方.例如,如果我有一个名为"news-item"的模块,则可以在该模块的定义的正下方放置任何必要的媒体查询样式.

我倾向于后者,但这意味着我将有更多单独的媒体查询(对于每个需要响应性调整的CSS逻辑块,都需要单独的媒体查询).

I am leaning towards the latter, but it would mean I'd have many more separate media queries (separate ones for each logical block of CSS requiring a responsive adjustment).

对此有何想法?

推荐答案

方法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 :-)

这篇关于CSS3媒体查询放在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆