使用css为具有特定类的最后一个元素设置样式

时间:2017-12-21 19:31:58

标签: html css less

我试图用活动类(*元素)设置最后一个div的样式,但是当它获得活动类时,我的代码样式最后一个div(x元素),如何使用less实现我的意图? / p>

HTML:

<div class="owl-stage">
    <div class="owl-item"></div>
    <div class="owl-item active"></div>
    <div class="owl-item active"></div>
    <div class="owl-item active"></div>*
    <div class="owl-item"></div>
    <div class="owl-item"></div>x
</div>

LESS:

   .owl-item {

            &.active {
                border-right: 1px solid @borderColor;

                &:last-of-type{
                    border-right:none;
                }
            }
        }

3 个答案:

答案 0 :(得分:3)

在您的情况下,last-of-typelast-child将始终引用最后一个元素,而不是具有活动类的最后一个元素。但是如果所有活跃元素相互跟随并且您有 3 活动元素,您可以尝试这样做:

&#13;
&#13;
.owl-item.active + .owl-item.active + .owl-item.active{
 font-size :30px;
 color:red;
}
&#13;
<div class="owl-stage">
    <div class="owl-item">1</div>
    <div class="owl-item active">2</div>
    <div class="owl-item active">3</div>
    <div class="owl-item active">4</div>
    <div class="owl-item">5</div>
    <div class="owl-item">6</div>
</div>
&#13;
&#13;
&#13;

但是如果元素的数量是未定义的并且没有关于活动类的特定逻辑,我认为你将无法为此找到CSS选择器。

您可以考虑使用JS解决方案:

&#13;
&#13;
$('.owl-item.active').last().css('color','red');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="owl-stage">
  <div class="owl-item">1</div>
  <div class="owl-item active">2</div>
  <div class="owl-item active">3</div>
  <div class="owl-item">4</div>
  <div class="owl-item  active">5</div>
  <div class="owl-item">6</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

last-of-type可能是问题,因为它按元素类型选择最后<div>。请尝试last-child

.owl-item {
    &.active {
        border-right: 1px solid @borderColor;
        &:last-child{ border-right:none; }
    }
}

答案 2 :(得分:0)

HTML CODE:

<div class="owl-stage">
    <div class="owl-item active">A</div>
    <div class="owl-item active">B</div>
    <div class="owl-item active">C</div>
    <div class="owl-item active">D</div>
    <div class="owl-item">E</div>
    <div class="owl-item">F</div>
</div>

jQuery CODE:

$( ".owl-stage .owl-item.active:last" ).css({
    backgroundColor : "yellow"
});

输出:

enter image description here