伪类:nextTo?

时间:2011-12-12 02:43:32

标签: css css3 css-selectors

假设我有以下HTML:

<ul>
    <li id="1">First issue.</li>
    <li id="2" class="error">Second issue.</li>
    <li id="3" class="error">Third issue.</li>
    <li id="4">Fourth issue.</li>
    <li id="5" class="error">Fifth issue.</li>
    <li id="6" class="error">Sixth issue.</li>
    <li id="7" class="error">Seventh issue.</li>
    <li id="8" class="error">Eighth issue.</li>
    <li id="9">Ninth issue.</li>
    <li id="10" class="error">Tenth issue.</li>
</ul>

以下CSS:

.error {
    background-color: rgba(255, 0, 0, 0.2);
}

我要做的是将样式中的第一个和最后一个<li>设置为与中间的其他<li>不同的样式。

例如,#2, #5, #10应该都匹配“序列中的第一个选择器”; #3, #8, #10应与“序列选择器中的最后一个”匹配。

我想将以下样式分别应用于“先顺序”和“最后顺序”:

.firstInSequence {
    border-radius-top-right: 10px;
    border-radius-top-left: 10px;
}

.lastInSequence {
    border-radius-bottom-right: 10px;
    border-radius-bottom-left: 10px;
}

我可以使用选择器在CSS中本地执行此操作吗?

3 个答案:

答案 0 :(得分:4)

正如其他答案中所述,您可以设置&#39;序列的第一个&#39;使用:not:first-child伪选择器:

:not(.error) + .error,
.error:first-child {
    border-top-right-radius: 10px;
    border-top-left-radius: 10px;
}

我想我已经找到了最后一个序列的解决方案&#39;在这种情况下圆角。它使用完全不同的方法来完成最终产品,但以类似的结果结束:

Rounded Corners on last of sequence

基本技术是使用radial-gradients应用伪元素列出.error.之后不是.error的项目,并将它们移到上一个.error之上)列表项目:

.error + :not(.error):before {
    content:'';
    display:block;
    width:10px;
    height:10px;
    position:absolute;
    top:-20px;
    left:0;
    background:-webkit-radial-gradient(100% 0,circle,transparent 10px,white 0);
}

.error + :not(.error):after {
    content:'';
    display:block;
    width:10px;
    height:10px;
    position:absolute;
    top:-20px;
    right:0;
    background:-webkit-radial-gradient(0 0,circle,transparent 10px,white 0);
}

确保liposition:relative;

最后,对于最后一个border-radius,请使用last-of-type

.error:last-of-type{
    border-bottom-right-radius:10px;
    border-bottom-left-radius:10px
}

Demo(Webkit仅为简单起见)

答案 1 :(得分:2)

我认为你可以将这些部分拼凑起来,但不是全部。但这是我的想法。

自由使用CSS3 not selectoradjacent sibling combinator

这些是我认为你有机会做的事情。

http://jsfiddle.net/PDQMg/

错误是列表中的第一个

li.error:first-child {  }
<li error />
<li noerror />
...
<li />

错误是在没有错误之后。

li:not(li.error) + li.error { }
<li noerror />
<li error />
...
<li />

错误是列表中的最后一个

li.error:last-child { }
<li />
...
<li class="error" />

答案 2 :(得分:2)

对于“按顺序排列”,您可以尝试这个,只要元素是相邻的:

演示:http://jsfiddle.net/WkxyP/

:not(.error) + .error,
.error:first-child {
    border-top-right-radius: 10px;
    border-top-left-radius: 10px;
}
  • :not(.error) + .error - 没有类“错误”的元素的“错误”类的下一个相邻元素
  • .error:first-child - 任何具有“error”类的元素,它是另一个元素的第一个子元素,对于上述选择器无法匹配的情况

认为涵盖了一切。不知道如何使用这个特殊的谜题“按顺序进行”。

顺便说一下:检查您的媒体资源名称,应该是border-top-left-radius而不是border-radius-top-left,依此类推。

相关问题