首页 > 解决方案 > Why :last-of-type does not work if there is another element at the end of the parent?

问题描述

Someone tell me, please, why can not I get the last item with text "STYLE ME" in the first case? I would like to receive a detailed explanation and I would not want to create extra wrappers as I did in my alternative version. Thanks.

.section > .block:last-of-type {
  border: 1px solid black;
}

/* Working alternative */
.block-wrap > .block:last-of-type {
  border: 1px solid black;
}
<b>Does not work:</b>

<div class="section">
  <div class="block">one</div>
  <div class="block">too</div>
  <div class="block">
    three
    <div class="block">nested (ignore me)</div>
  </div>
  <div class="block">STYLE ME</div>
  <div class="line">{Line}</div>
</div>

<hr>

<b>If you delete .line, it works:</b>

<div class="section">
  <div class="block">one</div>
  <div class="block">too</div>
  <div class="block">
    three
    <div class="block">nested (ignore me)</div>
  </div>
  <div class="block">STYLE ME</div>
</div>

<hr>

<b>Working alternative:</b>

<div class="section">
  <div class="block-wrap">
    <div class="block">one</div>
    <div class="block">too</div>
    <div class="block">
      three
      <div class="block">nested (ignore me)</div>
    </div>
    <div class="block">STYLE ME</div>
  </div>
  <div class="line">{Line}</div>
</div>

标签: htmlcss

解决方案


推荐阅读