Html 将 css 样式应用于子元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18199796/
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
Apply css style to child element
提问by Mayank Pandya
Here is an sample example
这是一个示例示例
<html>
<head>
<style>
.test > input { //this is wrong.
color:red;
}
</style>
</head>
<body>
<div class="test">
<div>
<input></input>
</div>
</div>
</body>
</html>
What I want to do is apply a style to input element. How to select a input element. with the help of div's css style name.
我想要做的是将样式应用于输入元素。如何选择输入元素。借助 div 的 css 样式名称。
回答by adnrw
you can just use .test input
(which will apply to every input in <div class="test">
).
您可以使用.test input
(这将适用于 中的每个输入<div class="test">
)。
Your CSS with >
only selects direct descendants
你的 CSS>
只选择直系后代
回答by chiliNUT
div.test input{
}
will style all inputs nested in the div of class test
将设置嵌套在类 test 的 div 中的所有输入的样式
div.test input:first-child{
}
will style only the first nested input.
将仅设置第一个嵌套输入的样式。
the ">" operator only styles directly descendent elements, so it will not style your inputs because you have div.test > div > input, the div in between div.test and input makes it so the input is not directly descendent to div.test
">" 运算符仅设置直接后代元素的样式,因此它不会设置您的输入样式,因为您有 div.test > div > input,div.test 和 input 之间的 div 使得输入不直接继承到 div。测试
回答by Ashis Kumar
If you want to apply style to input using div with class="test", you can do like this
如果您想使用带有 class="test" 的 div 将样式应用于输入,您可以这样做
<style>
.test > div > input {
color:red;
}
</style>
回答by TheBaj
As none of the other answers have mentioned this before, for this particular case you could also use the *
selector. It matches descendants that are grandchildren or later descendants. You would use it like so: .test * input
.
由于之前没有其他答案提到过这一点,对于这种特殊情况,您也可以使用*
选择器。它匹配作为孙子或以后的后代的后代。你会使用它,像这样:.test * input
。