问题
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!
回答1:
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>
回答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.
来源:https://stackoverflow.com/questions/7126531/css-selector-if-exist-adjacent-sibling