Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have specific CSS if a class is after another element with a particular ID

I have this scenario:

<div id="parent">
   <div id="a"></div>
   <li class="b"></li>
</div>

In my case, I want to add margin-top: 5px; to class b only if it is after id a. Note that these are not children, but within the same element.

I would like an approach using pure CSS or CSS3 and without the need to use LESS or SASS. I know that this might be possible using JavaScript or jQuery as well, was just wondering if it can be done in CSS and how.

like image 739
Ryan S Avatar asked Dec 06 '22 01:12

Ryan S


1 Answers

You can use the adjacent sibling selector. Following will select all elements with class .b that follow element with id #a:

#a + .b {
  margin-top: 5px;
}

Adjacent sibling selector is part of the CSS 2.1 spec and is supported in IE7+

Read more about CSS child and sibling selectors in here: http://css-tricks.com/child-and-sibling-selectors/

Demo: http://jsfiddle.net/76qJm/3/

like image 51
Henri Hietala Avatar answered Apr 30 '23 23:04

Henri Hietala