Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I target only elements that are followed by another (specific) element?

I have some code that is generated by a Drupal view. It looks like this (stripped down for clarity):

<div class="group_content">
  <h3>Header Link</h3>
  <div class="row odd">Here's some content</div>
  <h3>Another Header Link</h3>
  <div class="row even">Here's some more content</div>
</div>

<div class="group_content">
  <h3>Header Link 2</h3>
  <div class="row odd">Here's some content 2</div>
</div>

Because this is generated by a CMS, there's a limit to what I can do about the rendered code - for example, I can't add an even/odd class to the h3 elements.

How can I (in css) target only the div class=row that is followed by another div class=row? If there are more than one row in a group, I need to add a bottom border to the div to act as a visual separator. So, using my example code, there would be a border applied to div class="row odd">Here's some content</div> because it has another row following it.

I'm a backend developer, so CSS is not my strong suit. We do need to support IE7.

like image 531
EmmyS Avatar asked Jun 05 '12 15:06

EmmyS


1 Answers

Modified Logic

Since you need IE7 support, place the border on the h3 element instead:

div.row + h3 {
    border-top: 1px solid black;
}

This will work in just about every modern browser, and IE7:

Fiddle: http://jsfiddle.net/jonathansampson/BjUf9/1/

Explicit Subjects in Selectors

If you insist on placing it only on every div.row but the last, that's a different story. You're asking about moving the subject of a selector, which is not currently possible, but will be when browsers implement Level 4 selectors:

div.row! + div.row {
    /* These styles apply to the first div.row
       $div.row + div.row is another potential 
       syntax */
}

:last-child, in IE9+

Since you cannot do that, what you can do is set a style for all div.row elements, adding your border, and then overriding that for any div.row:last-child which will remove that border for any div.row that is the last element in its parent:

div.row {
    border-bottom: 1px solid #333;
}
div.row:last-child {
    border-bottom: 0px;
}

Fiddle: http://jsfiddle.net/jonathansampson/BjUf9/

I should note that this will not work in IE7, unfortunately. But the modified logic presented in the first solution should take care of you there.

like image 82
Sampson Avatar answered Nov 11 '22 16:11

Sampson