CSS selector if exist adjacent sibling [duplicate]
Asked Answered
P

2

15

I have the following (simplified) HTML structure

<td> 
    <DIV class="t-numerictextbox">
        <DIV class="t-formatted-value">$0.00</DIV>
        <INPUT id="MyObj_PropertyName class="t-input" name="MyObj.PropertyName">
    </DIV>
    <SPAN class="field-validation-error" data-valmsg-for="MyObj.PropertyName">blah blah</SPAN> 
</td>

What I'd like to do is set the background color to the parent div.t-numerictextbox to be red IF the span element also exist. What is the css syntax to do this conditional select on an adjacent sibling?

BTW, I need this has to work for IE 8.

Background, if you're curious:

I have an asp.net MVC application and am using the Telerik MVC NumericTextBox Control. When I have ModelState validation errors, the MVC framework automatically inserts a class="input-validation-error" attribute on the element, and the stylesheet picks this class up to highlight the element in red. However, it doesn't work for the Telerik MVC Control (I assume because Telerik's javascript overwrites this).

Thanks!

Panegyric answered 19/8, 2011 at 19:35 Comment(1)
The accepted answer at #29662509 is probably a better solution to this problem than the accepted answer here, other than the requirement for support in IE8.Milena
N
29

It is possible to place the span before the div in the html, and then position it with css.

Then use a css adjacent sibling selector to select the div adjacent to the span.

Finally put a position absolute on the span, and give it a top:..px to get it below the div.

So you get the following:

span + div {
  background-color:red;
}
<td> 
  <span class="field-validation-error" data-valmsg for="MyObj.PropertyName">blah blah</span> 
  <div class="t-numerictextbox">
    <div class="t-formatted-value">$0.00</div>
    <input id="MyObj_PropertyName" class="t-input" name="MyObj.PropertyName">
  </div>        
</td>
Nevins answered 19/8, 2011 at 19:56 Comment(0)
S
2

CSS cant do that. You could style the span if the div.t-numerictextbox exist, but not the other way around. This is a limitation of css, but will probably never change.

Shuping answered 19/8, 2011 at 19:59 Comment(1)
13 years later we have developer.mozilla.org/en-US/docs/Web/CSS/:has for this :)Suellen

© 2022 - 2024 — McMap. All rights reserved.