css - 带有 anchor 标记的最后类型在 CSS 中不起作用

标签 css

<分区>

为什么要在 <a> 标签上管理用于 last-of-type 的 css 样式?

以及如何使最后一个 .block 具有 margin-right: 3em<a> 标记元素具有 margin-right: 1em

.wrapper {
    margin-top: 1em;
    display: flex;
    justify-content: flex-start;
    background-color: silver;
}
.block {
    width: 2em;
    height: 2em;
    background-color: teal;
    line-height: 2;
    margin-right: 1em;
    text-align: center;
}
.block:last-of-type {
    margin-right: 3em;
}
.end {
    line-height: 2;
    width: 3em;
    height: 2em;
    background-color: red;
    text-align: center;
}
<div class="wrapper">
    <a href="#" class="block">A</a>
    <div class="block">A</div>
    <div class="block">A</div>
    <div class="block">A</div>
    <div class="end">End</div>
</div>

最佳答案

发生这种情况是因为 a 是其父级标签类型的最后一个。

换句话说,选择器.element:last-of-type 不会选择类为.element 的最后一个元素。相反,它选择一个元素,该元素应用了 .element并且同时是 sibling 中该类型的最后一个。

考虑以下示例:

.element,
.square {
  display: inline-block;
  vertical-align: middle;
  width: 20px;
  height: 20px;
  background: red;
}

.element:last-of-type {
  background: blue;
}
<div>
  <!-- is last of type "p" AND has ".element" 
       class applied - will be matched -->
  <p class="element"></p>
  <span class="element"></span>
  <span class="element"></span>
  
  <!-- last of type "span" and has ".element" 
       class applied - will be matched -->
  <span class="element"></span>

  <!-- last of type, but does NOT have an ".element" 
       class applied - will NOT be matched -->
  <a class="square"></a>
</div>

关于css - 带有 anchor 标记的最后类型在 CSS 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57314314/

相关文章:

javascript - 带关闭按钮的输入文本字段

javascript - css 在右侧对齐多行 contenteditable 内容

javascript - 如何找出创建 bootstrap-material 的位置

css - 如何根据其顶级父类修改类的行为?

html - 第一个 child 选择器不工作

css - 在 HTML5 中预加载音频需要时间

html - 页脚不会留在我的某个页面的底部

html - CSS 网格行具有不同的宽度

html - CSS根据大小定位差异

html - 使用关键帧动画从左到右动画背景填充一一