:last-child vs :last-of-type
We can often do some pretty funky stuff with nth-child selectors but sometimes we just need to use a simple :last-child
to keep the DOM layout clean.
Take this structure for example:
We are placing two blocks of content next to one another, keeping them inline-blocks to accommodate a variable number of items appearing next to one another. We also have a button below, that would lead to our primary action. This button ought to be the same width as the total width of the blocks laid side to side. Obviously, the margin on the last block needs to be removed so we don’t have the overhang on the right as shown in the pen below.
https://codepen.io/maneeshc/pen/xbJvOV
Using article:last-child{ margin-right:0; }
we would expect the last-child that is an article to have the margin of 0. But the last child selector is too specific for that. :last-child, literally means the very last child within that DOM node So the first qualifier is position in DOM tree, the second is the selector element it needs to match, in this case, <article>
.
Have a look at the structure again and you’ll see why this selector does not work, the last child is in fact the <div>
holding our button. Thus, the browser will look for the last child, and then check if its an <article>
element. Its not. Thus no joy.
:last-of-type to the rescue
The :last-of-type
selector is a better option here. It is much less specific because of its conditional being type. It looks at the last occurring instance of its matching selector and ignores what ever comes after. Thus, we can achieve the effect we are looking for like so:
https://codepen.io/maneeshc/pen/OPwKmw