【问题标题】:First-child and last-child pseudo property with CSS3CSS3 的第一个孩子和最后一个孩子的伪属性
【发布时间】:2012-06-23 22:59:52
【问题描述】:

我尝试使用第一个子项和最后一个子项创建样式,但遇到了问题。

当我使用first-child时,因为之前有strong item,样式不适用。但我的最后一个孩子工作得很好。

HTML:

<br />
<h2 class="title_block">Info <strong>1</strong>
    <span class="title_block_info">+2</span>
    <span class="title_block_info">+1</span>
</h2>​

CSS:

h2 .title_block_info,
h2 strong {
    border: 1px solid #000;
}
h2 .title_block_info:first-child {
    border-radius: 10px 0 0 10px;
}
h2 .title_block_info:last-child {
    border-radius: 0 10px 10px 0;
}​

此处示例:http://jsfiddle.net/mYKRW/

有人知道为什么会这样吗?

谢谢,

【问题讨论】:

    标签: html css css-selectors


    【解决方案1】:

    这是因为你有一个“强”标签作为第一个孩子,而不是你想要的 title_block_info 类。 first-child 仅在它实际上是元素的第一个子元素时才有效。

    这行得通

    <h2 class="title_block">
        <span class="title_block_info">+2</span>
        <span class="title_block_info">+1</span>
    </h2>​
    

    http://jsfiddle.net/mYKRW/1/


    如果你需要在那里的强文本,你可以试试这个,注意我是如何将你的两个跨度标签包装在另一个跨度标签中的。这将允许您使用第一个孩子和最后一个孩子

    h2 .title_block_info,
    h2 strong {
        border: 1px solid #000;
    }
    h2 span .title_block_info:first-child {
        border-radius: 10px 0 0 10px;
    }
    h2 span .title_block_info:last-child {
        border-radius: 0 10px 10px 0;
    }​
    
    <h2 class="title_block">
        Info <strong>1</strong>
        <span>
          <span class="title_block_info">+2</span>
          <span class="title_block_info">+1</span>
        </span>
    </h2>​
    

    http://jsfiddle.net/mYKRW/6/


    最后你可以使用first-of-type伪类,如果你想保持你的html完全符合你的要求,只需改变你的css。

    h2 .title_block_info,
    h2 strong {
        border: 1px solid #000;
    }
    h2 .title_block_info:first-of-type {
        border-radius: 10px 0 0 10px;
    }
    h2 .title_block_info:last-of-type {
        border-radius: 0 10px 10px 0;
    }​
    

    http://jsfiddle.net/mYKRW/9/

    【讨论】:

    • 没错,我很着急。妻子把我踢出电脑去踢足球……谢谢你的接球。
    【解决方案2】:

    :first-child 伪类从选择器.title_block_info 中选择第一个匹配元素如果也是:first-child父元素;正如您所注意到的,这不起作用,因为还有另一个元素是父元素的第一个子元素。

    在您的情况下,您可以删除在 DOM 中占据 :first-child 位置的 strong 元素,或者您可以改用 :first-of-type 伪类:

    h2 .title_block_info:first-of-type {
        border-radius: 10px 0 0 10px;
    }
    

    JS Fiddle demo.

    如果您的 HTML 将保持类似的可预测性(.title_block_info 元素将始终跟随 :first-child 元素),您可以改为:

    h2 :first-child + .title_block_info {
        border-radius: 10px 0 0 10px;
    }
    

    JS Fiddle demo.

    参考资料:

    【讨论】:

    • 只是为了保持一致性,与:last-of-type匹配。兼容性与:last-child完全相同。
    猜你喜欢
    • 2013-05-25
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 2013-03-12
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多