2

In css there is the adjacent selector + - however does anyone know how I would target the first element in that selector.

i.e. I want to target the <div> in the following selector:

div + p

Thanks in advance

3
  • 4
    The simple answer is "you can't". If you show the relevant HTML, we might be able to find a working selector.
    – thirtydot
    Jun 12, 2012 at 11:36
  • Also, why is purpose of discussing around div + p. You can just do anything like div {..}
    – Ashwin
    Jun 12, 2012 at 11:37
  • there is a selector to get the first-child but not for the first element. Jun 12, 2012 at 12:05

2 Answers 2

0

There no css selector for this but you can achieve this some css & html manipulation. Write like this:

HTML

<div class="parent">
   <p>hover me</p>
   <div>hello</div>
</div>

CSS

.parent{
    -moz-box-orient:vertical;
    -moz-box-direction:reverse;
    display: -moz-box;
    -webkit-box-orient:vertical;
    -webkit-box-direction:reverse;
    display: -webkit-box;
    box-orient: vertical;
    box-direction: reverse;
    display:box;
}
p{
    color:red;
}
p:hover + div{
    color:green;
    font-size:30px;
}

Check this http://jsfiddle.net/LEh2W/1/

May be that's help you but it's not work in IE.

2
  • I don't think it's wise to assume that the elements are stacked vertically.
    – BoltClock
    Jun 12, 2012 at 11:57
  • But you get the effect what you want.
    – sandeep
    Jun 12, 2012 at 11:58
0

If those divs are to be contained inside another element, maybe you could use this selector:

http://w3schools.com/cssref/sel_firstchild.asp

div:first-child {  background-color:yellow; }

So this would "select and style every div element that is the first child of its parent". So, assuming your div was the first child of its parent you could use this. But still, I don't see the practical reason to do this. I'd recommend simply setting a class for those divs and using the class selector.

2
  • 2
    div + p implies that div and p share the same parent, and thus p cannot be the first child.
    – BoltClock
    Jun 12, 2012 at 11:53
  • Yes, but what the poster is looking for is how to select the <div>. In my answer I just copied the example from the w3cschools link, but I'll edit it for clarity since you mention it. Cheers.
    – Rorok_89
    Jun 12, 2012 at 12:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.