EmmyS
EmmyS

Reputation: 12148

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.

Upvotes: 11

Views: 26491

Answers (3)

Jashwant
Jashwant

Reputation: 29025

This works for me on ie7 and others

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

Upvotes: 0

Sampson
Sampson

Reputation: 268492

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.

Upvotes: 11

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123438

you could revert the logic and apply a border-top to .row + .row elements

.row + .row {
   border-top : 1px #ccc solid;
}

the adjacent sibling selector (+) works fine on IE7+

Upvotes: 3

Related Questions