父级而不是子级的CSS样式? [英] CSS style for parent instead of child?
问题描述
我正在使用jquery将我从服务器获取的html插入div。根据div的内容,我想调整容器的样式。我写了一个简单的html测试。当它有X个子项时,我如何告诉CSS应用此站点?谷歌搜索后,我尝试:has和:contains都没有工作。我不想将样式保留在JS中,因为CSS更有意义。
I am using jquery to insert html I get from the server into a div. Based on the div contents i'd like to adjust the syle of the container. I wrote up a simple html test. How do I tell css to apply this site when it has X child? After googling I tried :has and :contains with neither working. I don't want to keep my styles in JS as css makes more sense.
演示: http://jsfiddle.net/wd9fk/
html
<div id="a"><div id="b">B</div></div>
<div id="a"><div id="c">C</div></div>
css
#a { height: 400px; border: 1px solid red; }
#b { height: 200px; }
#a :has #b { height: 300px; border: 1px solid blue; }
推荐答案
您根本无法遍历CSS中的DOM。您将需要使用JavaScript。
You simply cannot traverse up the DOM in CSS. You will need to use JavaScript.
此处是解释原因的文章: http://snook.ca/archives/html_and_css/css-parent-selectors
Here is an article explaining why: http://snook.ca/archives/html_and_css/css-parent-selectors
长话短说,这是由于与浏览器读取CSS的方式相同,并且通过引入CSS,它将使性能降低10倍(至少!),因为它需要多次读取每个节点以查看其是否适合
Long story short, it's due to the way CSS is read by the browser, and by introducing it, it would increase the performance hit by a factor of ten (at least!), because it would need to read every single node multiple times to see whether or not it fits the profile.
这是一个不错的主意,但是根本不可行。
It's a nice thought, but it's simply not viable.
这篇关于父级而不是子级的CSS样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!