1

Using the ":: after" selector with the "+" direct selector

I have this basic HTML structure:

<div class="cotnainer">
    <div class="left">  1 </div>
    <div class="right"> 2 </div>
    <div class="right"> 3 </div>
    <div class="left">  4 </div>
    <div class="right"> 5 </div>
    <!-- continuing on in a variable order -->
</div>

      

I need to style ::after

the last element of each type before the class changes sides.
those. I need to style 1, 3 and 4 in the above example
These elements will be generated dynamically

I've tried CSS selector like:

.right + .right::after, .left + .left::after { ... }
//this misses the individual elements

.right::after, .left::after { ...apply style... }
.right::after + .right, .left::after + .left { ...remove ::after style from preceeding elements... }
//this was an attempt to remove the generally applied style from preceeding elements

      


Any help, ideas or suggestions would be appreciated.

Change: . Since this question remained a problem for me, I started a bounty to continue looking for solutions and ideas to achieve the desired result.

+3


source to share


3 answers


CSS cannot do this. The correct solution is to group your lines; use meaningful semantic HTML code whenever possible.



ul {
  margin: 0;
  padding: 0;
  list-style-type: none;
}
.left {
  background: #6AF;
}
.right {
  background: #6CF;
}
.left > li:last-child::after {
  content: " (last child of .left)";
}
.right > li:last-child::after {
  content: " (last child of .right)";
}
      

<div class="cotnainer">
  <ul class="left">
    <li>1</li>
  </ul>
  <ul class="right">
    <li>2</li>
    <li>3</li>
  </ul>
  <ul class="left">
    <li>4</li>
  </ul>
  <ul class="right">
    <li>5</li>
  </ul>
</div>
      

Run codeHide result


I used ul / li in the example above, but see if there is a better element that matches the semantics.

+1


source


Unfortunately, CSS does not provide a "last-of-class" selection. Consider using a specific class for targeting with :: after or you can use some kind of JavaScript to choose from.



+1


source


As far as I know, I don't think you can do this with CSS alone. It looks like Boris is right.

.left + .right,
.right + .left {
    color:red;
}

      

Most likely it will. You will learn something new every day!


You can do it with jQuery, however, with something like:

JQuery

var lastElemHasClassLeft = false;
    $('.cotnainer > div').each(function(key, val) {
    if (lastElemHasClassLeft != $(this).hasClass('left')) {
        $(this).addClass('change');
    }
    lastElemHasClassLeft = $(this).hasClass('left');
});

      

CSS

.change::after {
    content: 'hello';
}

      

The spell is here: http://jsfiddle.net/2hxxhumq/

0


source







All Articles