Chris Hanson
Chris Hanson

Reputation: 731

:last-of-type when type is wrapped by another element

Lets say I have 3 fieldsets and I want 30px margin under all of them except the last fieldset.

.wrapper fieldset {
  margin-bottom: 30px;
}

.wrapper fieldset:last-of-type {
  margin-bottom: 0;
}

<div class="wrapper">
  <fieldset>...</fieldset>
  <fieldset>...</fieldset>
  <fieldset>...</fieldset>
</div>

That's ok, but now what if my fieldsets are wrapped in an arbitrary element eg:

<div class="wrapper">
  <ANY>
    <fieldset>...</fieldset>
  </ANY>

  <ANY>
    <fieldset>...</fieldset>
    <fieldset>...</fieldset>
  </ANY>
</div>

Now I have no margin on the first fieldset. I know why this happens, but I don't know a solution. Any help would be appreciated, cheers.

Upvotes: 1

Views: 112

Answers (2)

Sarhanis
Sarhanis

Reputation: 1587

Here's a working example. Need to take into account multiple elements, which is why the container of the fieldset needs to be taken into account.

.wrapper fieldset {
  margin-bottom: 30px;
}

.wrapper *:last-child fieldset:last-of-type {
  margin-bottom: 0px;
  color: pink;
}
<div class="wrapper">
  <div>
    <fieldset>#1 element</fieldset>
  </div>

  <div>
    <fieldset>#2 element</fieldset>
    <fieldset>#3 element</fieldset>
  </div>

  <footer>
    <fieldset>#4 element</fieldset>
    <fieldset>#5 element</fieldset>
  </footer>

  <div>
    <fieldset>#6 element</fieldset>
  </div>
</div>

Upvotes: 2

Liu Dongyu
Liu Dongyu

Reputation: 904

try only-child selector. jsbin

.wrapper fieldset {
  margin-bottom: 30px;
}

.wrapper fieldset:last-of-type {
  margin-bottom: 0;
}

.wrapper fieldset:only-child {
  margin-bottom: 30px;
}

Upvotes: 0

Related Questions