【问题标题】:How to add different color backgrounds in a html if block?如何在 html if 块中添加不同的颜色背景?
【发布时间】:2021-10-15 00:19:27
【问题描述】:

我正在使用烧瓶来提供 html 服务。在下面这段代码中:

{% if terms|length > 1 %}
        <div class="term">
        {% for term in terms %}
            {{ term }} &nbsp;&nbsp;
        {% endfor %}
        </div>
    {% endif %}

'terms' 最初是一个简单的项目列表['a', 'b', 'c']

当前 div class="term" 标记在迭代值时为每个术语添加相同的背景颜色。现在,这些术语变成了一个元组列表,其值如下:

('a': 1)
('b': 2)
('c': 3)

我想根据 a、b、c 的值 1、2、3 添加不同的颜色。 '1' 给出一个核心,'2' 给出另一种颜色,'3' 也给出另一种颜色。

当前样式表有一个条目:

div.term {
    background-color:mintcream;
} 

html和css如何实现这个效果?

编辑:根据 trimkas 的建议,我添加了 css 定义:

div.term.term-count-1 {
    background-color:green;
}
div.term.term-count-2 {
    background-color:lightblue;
}
div.term.term-count-3 {
    background-color:deepskyblue;
}
div.term.term-count-4 {
    background-color:blueviolet;
}

【问题讨论】:

    标签: html css flask


    【解决方案1】:

    {% for term in terms %} 循环内移动包装div,并向包含当前迭代次数(索引)的div 添加一个类。

    {% if terms|length > 1 %}
        {% for term in terms %}
        <div class="term term-count-{{loop.index}}">
            {{ term }} &nbsp;&nbsp;
        </div>
        {% endfor %}
    {% endif %}
    

    然后通过.term-count-0.term-count-1等以您需要的方式在CSS中引用。

    【讨论】:

    • trimkas,请查看我在上面编辑的新 CSS 定义。但是颜色没有变化。 loop.index 自动映射到 0, 1, 2, ...?
    • @marlon 您的Css定义是正确的,但是,请注意我发送的代码,您还需要更改html(移动循环内的div,并在循环内迭代当前索引类名)注意&lt;div class="term term-count-{{loop.index}}"&gt;这一行,那么你的CSS将是有效的,它应该可以工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 2023-01-09
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多