【问题标题】:Rails - How do I ensure my styles take precedence over Bootstrap?Rails - 如何确保我的样式优先于 Bootstrap?
【发布时间】:2015-03-12 11:55:20
【问题描述】:

我确定这是一个非常简单的问题,但我找不到直接的答案,所以想在这里问。

我正在使用 Bootstrap 构建一个网站,但希望我的自定义样式优先于 Bootstrap 的。

我想这可能就像调整我的 application.css.scss 文件中的顺序一样简单,但是我的修修补补还没有找到解决方案。

目前这个文件如下:

/*
 * 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
 */

@import "bootstrap-sprockets";
@import "bootstrap";

我刚刚开始构建这个网站,并且有几个 Bootstrap 网格列,我想从中删除填充。另一个,我添加了背景图片和高度,没问题。以下代码来自home.css.scss

.col-md-4 {
  background: url('http://i.imgur.com/xxxxxxxxxxxx.jpg');
  height: 1000px;
} //both of which work

.col-md-8 {
  padding: 0px 0px 0px 0px;
} //which is overridden by Bootstrap's default styling

正如我所说,希望这是一个真正简单的解决方案,不会花费太多精力来回答。感谢任何帮助!史蒂夫。

【问题讨论】:

  • 很好的阅读,我已经用它找到了我的问题的答案。由于类匹配,Bootstrap 因其在级联中的位置而优先。通过将@import "bootstrap-sprockets"; @import "bootstrap"; 移动到home.css.scss 的顶部,我的样式优先。非常感谢@BroiSatse。

标签: html css ruby-on-rails twitter-bootstrap asset-pipeline


【解决方案1】:

使用@BroiSatse 的重要链接得出答案:http://vanseodesign.com/css/css-specificity-inheritance-cascaade

由于 Bootstrap 和我的代码都引用了 .col-md-8 类,Bootstrap 的样式由于其位于级联中而优先。

通过将@import "bootstrap-sprockets"; @import "bootstrap";application.css.scss 移动到home.css.scss 的顶部,我的样式就会优先。一切正常!谢谢大家的帮助。

【讨论】:

    【解决方案2】:

    您可以使用 !important 。 它说什么; '这很重要,忽略后续规则和任何常见的特殊性问题,应用此规则!'

    p {
        color: red !important;
    }
    #thing {
        color: green;
    }
    <p id="thing">Will be RED.</p>

    例如:Demo

    参考:Here

    【讨论】:

    • 使用!important是有风险的,只有在没有其他方法可用时才应该使用。
    • @GaneshSalunkhe - 在 C++ 中使用 goto 也是一种解决方法。放置!important 是一种不好的做法——这意味着开发人员不了解 CSS 的特殊性并试图从 CSS 中摆脱 C。级联是美丽的,不要扼杀它。
    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    • 1970-01-01
    • 2011-03-22
    • 2010-10-20
    • 1970-01-01
    相关资源
    最近更新 更多