CSS 选择器如果存在相邻的兄弟
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7126531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CSS selector if exist adjacent sibling
提问by Raymond
I have the following (simplified) HTML structure
我有以下(简化的)HTML 结构
<td>
<DIV class="t-numerictextbox">
<DIV class="t-formatted-value">span + div {
background-color:red;
}
.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?
我想要做的是将父 div.t-numerictextbox 的背景颜色设置为红色,如果 span 元素也存在。在相邻的兄弟节点上执行此条件选择的 css 语法是什么?
BTW, I need this has to work for IE 8.
顺便说一句,我需要它适用于 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).
我有一个 asp.net MVC 应用程序并且正在使用 Telerik MVC NumericTextBox 控件。当我有 ModelState 验证错误时,MVC 框架会自动在元素上插入一个 class="input-validation-error" 属性,样式表会选择这个类以红色突出显示该元素。但是,它不适用于 Telerik MVC 控件(我假设是因为 Telerik 的 javascript 覆盖了它)。
Thanks!
谢谢!
回答by vanErp
It is possible to place the span before the div in the html, and then position it with css.
可以在html中将span放在div之前,然后用css定位。
Then use a css adjacent sibling selector to select the div adjacent to the span.
然后使用css相邻兄弟选择器选择与span相邻的div。
Finally put a position absolute on the span, and give it a top:..px
to get it below the div.
最后在跨度上放置一个绝对位置,并给它一个top:..px
使其低于 div。
So you get the following:
所以你得到以下信息:
<td>
<span class="field-validation-error" data-valmsg for="MyObj.PropertyName">blah blah</span>
<div class="t-numerictextbox">
<div class="t-formatted-value">##代码##.00</div>
<input id="MyObj_PropertyName" class="t-input" name="MyObj.PropertyName">
</div>
</td>
##代码##
回答by Gerben
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.
CSS无法做到这一点。如果 div.t-numerictextbox 存在,您可以设置跨度的样式,但反之则不行。这是 css 的限制,但可能永远不会改变。