【问题标题】:Use CSS Child and Last Selector on same element在同一元素上使用 CSS Child 和 Last Selector
【发布时间】:2016-02-18 23:38:35
【问题描述】:

我在引导程序panel-footer 中有不同的使用字形图标的链接,如下所示:

<div class="panel-footer">
    <a href class="pull-right">
        <span class="glyphicon glyphicon-chevron-up"></span>
    </a>
    <a href class="pull-right margin-right">
        <span class="glyphicon glyphicon-pencil"></span>
    </a>
</div>

如您所见,我需要使用我自己的 margin-right 类为最后一个 a-child 元素应用额外的边距:

.margin-right {
    margin-right: 5px;
}

上面的代码可以在这个plunk找到。


由于这似乎是一种丑陋的解决方法,我考虑将 CSS 子选择器与 :last-element 选择器结合使用来选择所需的元素并应用所需的 margin-right。我想出的是这样的:

<div class="panel-footer">
    <a href="#" class="pull-right">
        <span class="glyphicon glyphicon-chevron-up"></span>
    </a>
    <a href="#" class="pull-right">
        <span class="glyphicon glyphicon-pencil"></span>
    </a>
</div>

我将 CSS 文件中的 margin-right 样式替换为以下内容:

.panel-footer > a:last-child {
    margin-right: 5px;
}

但是,这不会产生想要的结果。如您在此plunk 中所见,没有将margin-right 应用于所需的子元素。

如何以我想要的方式选择最后一个子元素并应用所需的margin-right?

【问题讨论】:

  • 这对我来说似乎是正确的,因为a 是您的最后一个孩子。你能创建一个演示吗?
  • 您是否将 display:block 或 inline-block 应用于元素?或者你可以试试 .panel-footer > .pull-right:last-child { display: inline-block;右边距:5px; }
  • 我怀疑这是一个特异性问题。该类将具有比伪类更高的特异性。
  • 您提供的代码可以正常工作。
  • @albert:这让问题变得非常清楚。最初发布代码时,您错过了panel-footer 的一部分。其中最后一个div 意味着a 不是最后一个孩子,因此您必须使用a:last-of-type。我在添加这个答案时感到有点不安,因为 worldojr 已经提供了这个作为解决方案(我知道他的推理是错误的,但仍然如此)。我撤回了我的近距离投票,因为这个问题现在可以重现了。

标签: html css twitter-bootstrap css-selectors


【解决方案1】:

使用:last-of-type 伪类代替:last-child:

.panel-footer a:last-of-type {
    margin-right: 5px;
}

【讨论】:

  • 我很抱歉,@Harry - 我看到你比我早 3 分钟到达那里,而我正在检查 CSS。
  • 不用担心@Rounin。无论如何,我不打算发布它,而且您不可能知道最初发布该内容的其他用户。他删除了他的答案,因为他的推理不正确。
猜你喜欢
  • 1970-01-01
  • 2011-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-03
  • 2016-06-24
相关资源
最近更新 更多