html - 覆盖 css 类创建一个新的 css 类

标签 html css overriding

这是一个一般性问题,给定一个 html 组件(例如一个表格),我想添加一个新的 css 类来覆盖当前的类。例如我想覆盖下表的td悬停,添加一个新类,以免影响其他使用公共(public)类的表:

html(使用引导类)

<table id="calDate" class="table table-striped table-bordered table-condensed table-hover alignCenter">
<tbody>
<tr>
<td>
<tbody>
</tbody>
table>

CSS

table {
max-width: 100%;
background-color: transparent;
border-collapse: collapse;
border-spacing: 0;
}

.table {
width: 100%;
max-width: 90%;
margin-bottom: 5px;
}

.table th,
.table td {
padding: 8px;
line-height: 20px;
text-align: left;
vertical-align: top;
border-top: 1px solid #dddddd;
}

.table-hover tbody tr:hover > td,
.table-hover tbody tr:hover > th {
 background-color: #f5f5f5;
}

我尝试覆盖最后一个类,创建一个名为 .alignCenter 的新类,尝试更改 td 悬停行为以及文本对齐,对齐有效但鼠标悬停在其上无效:

.alignCenter {

}

.alignCenter-hover tbody tr:hover > td,
.alignCenter-hover tbody tr:hover > th {
 background-color: #df8505;
}

.alignCenter th, .alignCenter td{
 text-align: center;
 }
  1. 创建新的 css 类覆盖现有类的常用方法是什么?
  2. 如何使用新创建的 css 类来更改 td 悬停行为,例如更改背景颜色?
  3. 在示例中,类 .table 具有最大宽度:100%;它在下面再次定义为 max-width: 90%;。表中使用了哪个最大宽度,为什么?

最佳答案

好吧,让我一一回答你的问题:

-1. What's the usual way to create a new css class overwhiting the existent classes?

您可以通过修改类本身或为同一元素上的另一个类添加不同的值(或内联样式)来覆盖它们。

-2. How can I use the new created css class to change the td hover behavior for example change the background color?

只需这样做:

tr:hover td {
    /* do hover stuff */
}

-3. In the example the class .table has max-width: 100%; and it's defined again below with max-width: 90%;. Which max-width is used in the table, and why?

在 CSS 中,它总是最近(最后)的命令将“获胜”。但是,您可以像这样使用 !important 覆盖它:

.table {
    /* ... */
    max-width: 90% !important;
    /* ... */
}    

还有更多:摆脱table-hover,这是不必要的;而是像这样设置它的悬停变体:

.table:hover {
    /* stuff goes here */
}

关于html - 覆盖 css 类创建一个新的 css 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23223239/

相关文章:

html - 如何使用 Bootstrap 嵌套列网格

c - 打开 .txt 文件进行写入时出现段错误

javascript - 将 javascript 变量添加到 html 错误未定义

javascript - 减小 a 框架 Canvas 的大小以显示其他 HTML 元素

css - 在 IE 11 的文本输入字段中更改光标

java - Java 中的@Override 注解

c++ - 为什么不覆盖基类函数?

HTML:两行文本居中垂直对齐

jQuery CSS 选择器背景

html - 在制作响应式组件时,您在什么时候将其拆分为两个组件?