【问题标题】:How to have different background color for each children of children如何为孩子的每个孩子设置不同的背景颜色
【发布时间】:2019-12-01 18:27:14
【问题描述】:

我想做一个类似风格的 reddit 评论。

这样:

<div>
  <div class="comment" style="background: white;">
    <div class="comment" style="background: grey;"></div>
    <div class="comment" style="background: grey;">
      <div class="comment" style="background: white;">
        <div class="comment" style="background: grey;"></div>
      </div>
    </div>
  <div class="comment" style="background: white;"></div>
</div>

我正在寻找适合我的情况

其实我的 html 代码是由 Rails 生成的,看起来像这样

<div class="comment_main-list>
  <div class="comment_list">
    <div class="comment">blabla</div>
    <div class="comment_main-list>
       <div class="comment_list>
         <div class="comment">answer to blabla</div>
       </div>
    </div>
  </div>
  <div class="comment_list">...</div>
</div>

我尝试过这样的事情

.comment_list{
  background: #ececec;
  .comment_list{
    background: #dfdfdf;
    .comment_list{
      background:  #ececec;
    }
  }

显然它有效,但我无法在未定义的时间内这样做,我试图查看 sass 中的循环,但我不知道如何提前知道评论的数量。

nth:childnth:type 也不能满足我的要求。

你知道我该怎么做吗?

谢谢

【问题讨论】:

  • 您是否有特定的颜色顺序?
  • 不是我只想使用两种颜色,而且孩子必须是父母的不同颜色。例如,如果父母是white,那么他的所有孩子都应该是gray,孩子的孩子应该是white
  • 我认为这可能与 stackoverflow.com/questions/8499496/… 重复
  • 与其尝试创建 CSS 逻辑解决方案,您能否配置 Rails 代码在循环和构建 HTML 时为背景颜色添加额外的类?

标签: html css sass


【解决方案1】:
<div>
  <div class="comment" style="background: white;">
    <div class="comment" style="background: grey;"></div>
    <div class="comment" style="background: grey;">
      <div class="comment" style="background: white;">
        <div class="comment" style="background: grey;"></div>
      </div>
    </div>
  <div class="comment" style="background: white;"></div>
</div>

在 CSS 上

 div:nth-child(1) {
      background: red;
 }
 div:nth-child(2) {
      background: blue;
 }

【讨论】:

  • 这不解决嵌套问题。它只针对第一个或第二个孩子的 DIV。
猜你喜欢
  • 2016-12-11
  • 2017-05-18
  • 2019-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-23
  • 2020-12-15
相关资源
最近更新 更多