过度使用内联CSS

问题描述

我有一个树形结构,可以在其中展开和折叠节点。每个节点都在顶部和左侧分配了内联CSS高度。顶部和左侧是在渲染期间根据节点的位置动态计算的。我想将节点的高度降低到40px,并通过节点的20px *位置来减少每个节点的顶​​部和左侧。如何使用CSS实现呢?我无权直接在进行计算的代码中进行更改。唯一允许修改方法是来自CSS文件

示例:

<div class="node" style="height: 62px; position: absolute; top: 0px;"></div>
<div class="node" style="height: 62px; position: absolute; top: 62px;"></div>
<div class="node" style="height: 62px; position: absolute; top: 124px;"></div>
<div class="node" style="height: 62px; position: absolute; top: 186px;"></div>
<div class="node" style="height: 62px; position: absolute; top: 248px;"></div>

这些是应用于每个节点顶部的内联CSS。我希望每个节点的顶​​部减少20 *节点索引。保持原样为第一个节点,第2个乘以20,第3个乘以40,第4个乘以60,依此类推。

非常感谢您提供任何帮助。

已更新:

使用Scss或更小版本可以实现吗?

解决方法

您可以编写一个外部CSS文件来做到这一点:

.node{
    height: 40px!important;
    margin-top: -20px;
    margin-left: 20px;
}

该代码将完成您的工作,但请不要忘记在CSS代码行中输入!important。如果外部CSS文件中有相同的CSS参数,则!important将覆盖内联CSS。

注意:内联CSS不会被删除,只会对外部CSS无效。所以别担心了。只需转到您的外部CSS文件,然后使用!important在此处提供新代码即可。

如果您不想使用!important,则可以在下面使用此代码,它也将正常工作。

.node{
    max-height: 40px;
    margin-top: -20px;
    margin-left: 20px;
}
,

通常,直接从CSS样式表覆盖内联属性的唯一方法是使用!important。另一种选择是使用其他约束或更改行为的属性。

在这种情况下,您可以使用负数transform: translate()margin将节点向上和向左移动,并用max-height约束高度。

您可以使用:nth-child()选择要更改的节点:

.node {
  max-height: 50px;
}

.node:nth-child(1) {
  transform: translate(0,-20px);
}

.node:nth-child(2) {
  transform: translate(-20px,-20px);
}

.node:nth-child(3) {
  transform: translate(-40px,-20px);
}

.node:nth-child(4) {
  transform: translate(-60px,-20px);
}

.node:nth-child(5) {
  transform: translate(-80px,-20px);
}

/** just for the example **/
.node {
  background: red;
  width: 20px;
  left: 100px
}
<div class="node" style="height: 62px; position: absolute; top: 0px;"></div>
<div class="node" style="height: 62px; position: absolute; top: 62px;"></div>
<div class="node" style="height: 62px; position: absolute; top: 124px;"></div>
<div class="node" style="height: 62px; position: absolute; top: 186px;"></div>
<div class="node" style="height: 62px; position: absolute; top: 248px;"></div>