将css类直接放在元素或其父元素上

时间:2015-05-07 20:43:56

标签: html css

我有一个div,我需要给它的一个孩子div上色。我正在考虑将CSS类设置为父div,而不是直接设置在子div上,因为我有一个已经有父类的引用的javascript类,所以我不需要查找子代。

这是一个糟糕的实践吗?它会在将来给我带来麻烦吗?

这是一个示例http://codepen.io/anon/pen/pJgzJp?editors=110

HTML:

这样更好吗

<div class="parent1 whatIPrefer">
  <div class="children1">
  </div>
</div>

大于

<div class="parent2">
  <div class="children2 meh">
  </div>
</div>

CSS

.parent1 {       宽度:200像素;       高度:200像素;     }

.children1{
  width:200px;
  height:200px;
}

.whatIPrefer .children1{
  background-color: gold;
}

.parent2{
  width:200px;
  height:200px;
}

.children2{
  width:200px;
  height:200px;
}

.meh{
  background-color: tomato;
}

更多上下文:我想在页面中以红色显示有问题的项目。可能有很多项目以这种方式着色,我的javascript代码为它着色它看起来像这样

for (var i = 0; i < this._report.WorksheetSectionIDs.length; i++) {
    var worksheetSection = this._report.GetWorksheetSection(i);

    if (worksheetSection._worksheet._grid.getColumns().length != columnsCount) {
        this.Errors.push("Worksheet " + worksheetSection._sectionID + " doesn't have the right number of columns.");
        worksheetSection.SetInErrorState();
    }
}

其中每个worksheetSection都有对父元素的引用,因此我可以轻松地为其添加一个类。

2 个答案:

答案 0 :(得分:1)

您的情况在很大程度上取决于您的使用案例。您没有提供太多上下文,因此这可能是定位您的孩子div的最佳或最佳应用。

您可以使用css的子选择器访问div的孩子:

.whatIPrefer > div { styles }

Here is an excellent article on selecting children of a parent element - 检查一下。

希望这会有所帮助。请在下面评论任何其他问题。感谢

答案 1 :(得分:0)

这取决于网络结构和元素,你是造型。例如,如果您知道,该标题只是一个,您可以直接设置标题样式,但是如果有更多标题具有不同的样式,例如正文中的标题,标题中的标题等等。在这种情况下,设置抛出父元素是好的。

在我的项目中,我总是设计抛出父元素,有时候它是无用的,但这是一个很好的做法,你永远不会知道,当你的网络需要新的元素时。

相关问题