#sidebar p {
font-style: italic;
text-align: right;
margin-top: 0.5em;
}
上面的样式只会应用于出现在 id 是 sidebar 的元素内的段落。这个元素很可能是 div 或者是表格单元,尽管它也可能是一个表格或者其他块级元素。它甚至可以是一个内联元素,比如 <em></em> 或者 <span></span>,不过这样的用法是非法的,因为不可以在内联元素 <span> 中嵌入 <p>。
一个选择器,多种用法
即使被标注为 sidebar 的元素只能在文档中出现一次,这个 id 选择器作为派生选择器也可以被使用很多次:
#sidebar p {
font-style: italic;
text-align: right;
margin-top: 0.5em;
}
#sidebar h2 {
font-size: 1em;
font-weight: normal;
font-style: italic;
margin: 0;
line-height: 1.5;
text-align: right;
}
我们尝试用上小节的知识点来实现:让view组件里面的所有text文本显示为红色。
<view>
<text>普通文本</text>
<text id="myid">ID选择器里面的文本</text>
</view>
<view id="myid2">
<text>普通文本</text>
</view>
/* 元素选择器 */
page{
background-color: gainsboro;
}
view{
background-color: aliceblue;
}
/* id选择器 */
#myid{
color: white;background-color: black;
}
#myid2 text{
color:red;
}
效果如下图