【问题标题】:How do I give one stylesheet precedence over the other with Rails?如何使用 Rails 让一个样式表优先于另一个样式表?
【发布时间】:2015-05-09 05:27:57
【问题描述】:

我一直在寻找所有地方,但我无法弄清楚如何让一个样式表优先于另一个。这就是我在app/assets/stylesheets/application.css 中的内容:

/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any styles
 * defined in the other CSS/SCSS files in this directory. It is generally better to create a new
 * file per style scope.
 *
 *= require_tree .
 *= require_self
 */

/* Master Reset */
body {
  background-color: #000;
}

我的控制器在同一目录中还有一个名为 welcome.scss 的文件,其名称为 welcome:

// Place all the styles related to the welcome controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/

body {
  background-color: orange;
}

h4 {
  color: #fff;
}

我希望我可以用welcome.scss 输出的内容覆盖application.css 的 CSS,但我的 HTML 输出按以下顺序排列它们:

<link rel="stylesheet" media="all" href="/assets/welcome.self-6767494a578e8cc2f59dd92fa7081a577973e0fdcd72f58e91863e405fcf1e4d.css?body=1" data-turbolinks-track="true" />
<link rel="stylesheet" media="all" href="/assets/application.self-8e112c6b70d20efd74388d7b26053c97e2b11700f8ef5d5b5f9d723770f2e869.css?body=1" data-turbolinks-track="true" />

这意味着application.css 正在覆盖我想要覆盖它的welcome.scss 中的橙色background-color。我尝试将application.css 中的require 指令移动到底部和各种东西(我以为我没有正确编写它们)。我已将它们移回最初的位置。我怎样才能包含welcome.scss 之后 application.css?

是的,我是 Rails 菜鸟。 :)

【问题讨论】:

    标签: css ruby-on-rails sass sprockets


    【解决方案1】:

    以下内容会将 application.css 放在顶部:

    *= require_self
    *= require_tree .
    

    【讨论】:

      【解决方案2】:

      您通常不希望在 application.css 中包含 CSS,而是仅将其用于指令。如果您确实在其中包含 CSS,Rails 将在所有指令之后包含它,无论您将它放在文件中的哪个位置,因此您的问题。

      我相信您可以使用指令require_self 来覆盖它并指定包含指令文件中的CSS 的顺序。您可以查看here 了解更多信息。

      【讨论】:

      • 我已经颠倒了顶部的*=require 指令,那么将CSS 放入application.css 有什么不好呢?这似乎是最有意义的,因为它现在将是第一个文件。我可以把我的结构东西和我的重置放在里面,这样它就会包含在所有页面中。
      • 查看我的更新 - 如果你以 require_self 开始你的指令,你的指令文件中的 CSS 将首先出现(这是你想要的)。
      • 谢谢,可爱!我会在几分钟内将其标记为答案(当我被允许时)。
      • 很高兴为您提供帮助。也许这只是风格或偏好的问题,但我喜欢清单文件只有指令而不是内容。我想只要你保持一切正常就可以了。
      猜你喜欢
      • 2016-04-25
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      • 1970-01-01
      • 1970-01-01
      • 2012-11-18
      • 2013-02-17
      • 1970-01-01
      相关资源
      最近更新 更多