本文章来给各位同学介绍关于CSS 派生选择器的用法与实例详解,希望些文章对各位同这会有所帮助哦。
通过依据元素在其位置的上下文关系来定义样式,你可以使标记更加简洁。在 CSS1 中,通过这种方式来应用规则的选择器被称为上下文选择器 (contextual selectors),这是由于它们依赖于上下文关系来应用或者避免某项规则。在 CSS2 中,它们称为派生选择器,但是无论你如何称呼它们,它们的作用都是相同的。
派生选择器允许你根据文档的上下文关系来确定某个标签的样式。通过合理地使用派生选择器,我们可以使 HTML 代码变得更加整洁。
比方说,你希望列表中的 strong 元素变为斜体字,而不是通常的粗体字,可以这样定义一个派生选择器:
代码如下
复制代码
li strong {
font-style: italic;
font-weight: normal;
}
请注意标记为 <strong> 的蓝色代码的上下文关系:
代码如下
复制代码
<p><strong>我是粗体字,不是斜体字,因为我不在列表当中,所以这个规则对我不起作用</strong></p>
<ol>
<li><strong>我是斜体字。这是因为 strong 元素位于 li 元素内。</strong></li>
<li>我是正常的字体。</li>
</ol>
在上面的例子中,只有 li 元素中的 strong 元素的样式为斜体字,无需为 strong 元素定义特别的 class 或 id,代码更加简洁。
再看看下面的 CSS 规则:
代码如下
复制代码
strong {
color: red;
}
h2 {
color: red;
}
h2 strong {
color: blue;
}
下面是它施加影响的 HTML:
代码如下
复制代码
<p>The strongly emphasized word in this paragraph is<strong>red</strong>.</p>
<h2>This subhead is also red.</h2>
<h2>The strongly emphasized word in this subhead is<strong>blue</strong>.</h2>
例1
代码如下
复制代码
<styletype="text/css">
ollistrong{
font-style:italic;
font-weight:normal;
}
olli{
color:blue;
}
</style>
<body>
<p><strong>我是粗体字,不是斜体字,因为我不在列表当中,所以这个规则对我不起作用</strong></p>
<ol>
<li><strong>我是斜体字。这是因为strong元素位于li元素内。</strong></li>
<li>我是正常的字体。</li>
</ol>
</body>
按照元素的位置进行指定样式。
例2
我在学习一个下拉菜单的时候遇到了这个问题. 整个菜单无法居中.
代码如下
复制代码
<div class="center_holder">
<div style="margin: 0 auto; width: 410px; text-align: center;">
<ul class="menu">
<li><a href="#">首页</a>
<ul>
<li><a href="#">test</a></li>
<li><a href="#">test</a></li>
<li><a href="#">test</a></li>
</ul>
</div>
</div>
.center_holder {
padding-top: 20px;
margin: 0 auto;
min-width: 500px;
max-width: 1100px;
text-align: center;
}
.menu {
height: 40px;
width: 610px;
background: #4c4e5a;
background: -webkit-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
background: -moz-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
background: -o-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
background: -ms-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
background: linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
.menu ul {
position: absolute;
top: 40px;
left: 0;
opacity: 0;
background: #1f2024;
-webkit-border-radius: 0 0 5px 5px;
-moz-border-radius: 0 0 5px 5px;
border-radius: 0 0 5px 5px;
-webkit-transition: opacity .25s ease .1s;
-moz-transition: opacity .25s ease .1s;
-o-transition: opacity .25s ease .1s;
-ms-transition: opacity .25s ease .1s;
transition: opacity .25s ease .1s;
}
然后我试图在menu中添加margin-left: auto; margin-right: auto;无果.
又试图在center_holder中添加.
最后试图在menu ul中使用,还是无果.
最后在高手指点下把 .menu { 加上margin:0 auto;
如
代码如下
复制代码
<div class="center_holder">
<div style="margin: 0 auto; width: 410px; text-align: center;">
<ul class="menu">
<li><a href="#">首页</a>
<ul>
<li><a href="#">test</a></li>
<li><a href="#">test</a></li>
<li><a href="#">test</a></li>
</ul>
</div>
</div>
问题解决了。