Question

Hope you can help me with this CSS trick.

Basically what I need is this kind of CSS

if 'container' has sibling 'mySibling' {
    #myDiv{
    }
}
if 'container' has no sibling {
    #myDiv{
    }   
}

For this HTML

<div id="mySibling"></div>
<div id="container">    
    <div id="myDiv"></div>
</div>

sibling sometimes will not be present, and I need different css for myDiv in these cases

Any help would be appreciated, I tried doing + and ~ selectors but I don't think I have proper logic.

Was it helpful?

Solution

You can do something like this:

#mySibling + #container #myDiv {
    background-color:blue;
}

Here is a fiddle showing it off: http://jsfiddle.net/Lzq3S/

Note, I've changed the ids to classes in the fiddle just to show the two sets of div elements, but you get the idea...

This breaks down to myDiv that is a child of container that is a sibling of mySibling.

OTHER TIPS

First off, make sure your html is correct; in your example, you forgot to specify whether you're using an id or a class! Possible options for your html:

<div id="container">
   <div class="mySibling"></div>  
   <div class="myDiv"></div>
</div>

or

<div id="container">
  <div id="mySibling"></div>  
  <div id="myDiv"></div>
</div>

For the sake of your example, we'll use id's, even though some would say it's better practice to use classes

Now for the CSS.

The + and ~ selectors operate in slightly different ways. The + selects adjacent siblings, while the ~ selects all siblings. Because CSS doesn't handle logic quite the same way as actual programming languages, you can't check to see if a container holds a certain element before applying styles, but you can use the sibling selectors to style elements that are next to certain other elements.

My suggestion:

.container #myDiv {
  /* Your styles for #myDiv */
}
.container #mySibling + #myDiv {
  /* Your styles for #myDiv it is next to #mySibling. 
     Will override the styles a */
}

You can check out an example here: http://jsfiddle.net/8r2TZ/. Note, I specified "myDiv" as a class, because I used it more than once, and my CSS reflects that.

If you do need to have a CSS rule for each case without relying on overriding, it's still possible, since there's a selector for elements with no siblings:

#mySibling + #container > #myDiv {
}

#container:only-child > #myDiv {
}

(You can even achieve compatibility with old IEs by using :first-child in lieu of :only-child since #mySibling comes first.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top