覆盖CSS样式 [英] Override CSS style

查看:126
本文介绍了覆盖CSS样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义一些CSS类,当应用于表时,将生成一些默认样式。



例如,我创建一个名为myTable的类:

  .myTable {
th {
background-color:#000;
}

td {
background-color:#555;
}
}

因此,任何具有.myTable类的表都将获得



我想如果另一个类被分配给一个单独的td,那么它会覆盖默认的样式。



所以如果我有另一个类:

  .red {background-color:red ; } 

还有一个表格:

 < table class = myTable> 
< th class =red>内容< / th>
< td>您好!< / td>
< / table>

我认为红色类会导致标题的背景是红色,黑色。事实并非如此。为了使这个类重写原始的,它必须在myTable类中定义如下:

  td.red { background-color:red; } 

我缺少这里的东西,还有另外一种方法,

$ p

解决方案

这个想法是使用哪种风格取决于两件事:选择器具体是什么,规则的位置(最新规则胜利)。示例:

  p {
background-color:red;
}

p {
background-color:blue;
}

段落将是蓝色的。另一个例子:

  body p {
background-color:red;
}

p {
background-color:blue;
}

段落将是红色的,因为body p >

编辑:也尽量避免使用!important。它是支持,但副作用是,你永远不可以覆盖它(永远)。因此,只有在真正极端的情况下,你无法知道如何构造足够规则(例如:通用print.css)。


I am defining some CSS classes which, when applied to a table, will generate some default styling.

For example, lets say I create a class called myTable:

.myTable {
  th {
    background-color: #000;
  }

  td {
    background-color: #555;
  }
}

So any table with the .myTable class would get those colors on th and td by default.

I thought that if another class were to be assigned to an individual td, then it would override the default style.

So if I had another class:

.red { background-color: red; }

And a table:

<table class=myTable>
  <th class="red">Content</th>
  <td>Hello!</td>
</table>

I thought that the "red" class would cause the background of the header to be red, rather than black. That is not the case. In order for this class to override the original, it has to be defined within the myTable class like so:

td.red { background-color: red; }

Am I missing something here, is there another way to do this so that I could have default styles that are more easily overridden?

解决方案

The idea is that which style to use depends on two things: how specific it the selector is, the position of rule (latest rule wins). Example:

p {
  background-color: red;
}

p {
  background-color: blue;
}

Paragraphs will be blue. Another example:

body p {
  background-color: red;
}

p {
  background-color: blue;
}

Paragraphs will be red since "body p" is more specific.

Edit: Also try to avoid using !important. It is supported but a side effect is that you can never override it (ever). Thus only use it in the really extreme cases where you have no way of knowing how to construct specific enough rules (e.g.: generic print.css).

这篇关于覆盖CSS样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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