Targeting an anchor tag

Which way is better and more efficient?

This way:

<a href="" target="_blank" title=""></a>

.nav a:nth-of-type(15) {
 background: red;
}
   <li><a href="" target="_blank" title=""></a></li>

.nav li:nth-of-type(15) a {
  background: red;
}

or Adding a class name to it.
https://jsfiddle.net/t930tdx5/66/

 <a class="link" href="" target="_blank" title=""></a>

.nav .link {
 background: red;
}

https://jsfiddle.net/7r3Lcf6p/19/

<li><a class="link" href="" target="_blank" title=""></a></li>

.nav .link {
  background: red;
}

Personally, I’d target them with an id property, as you know exactly what you’re getting - so long, of course, that you’re checking it is actually there.

Of the two methods above though, I’d see class as the more reliable of the two. The a:nth-of-type() seems horribly fragile to me, especially if you end up working with dynamically generated code at any point.

I’m sure there are ways of working reliably with nth-of-type() and perhaps someone with more experience will come along and outline the kind of patterns that need to be employed in order to do that.

1 Like

Thank you for your opinion and thoughts on this, I would like to get others opinion and thoughts on this also and see what everyone else thinks.

I agree with Chris - using nth-of-type is a more fragile technique. However, investigating the purpose of why you are targeting that one particular link, will help to give further information from which better advice can be given.

You would recommend going from this:

.nav a:nth-of-type(5n) {
  margin-right: 0;
}

.nav a:nth-of-type(15)  {
 background: red;
}

To this?

.nav a.link15,
a.link10,
a.link5 {
  margin-right: 0;
}

.nav .link15 {
  background: red;
}

On lack of information, I would recommend neither until my question has been answered.

Why are you targeting that one particular link?

2 Likes

Let me do some more research.

I recommend using a grid system, where you tell the CSS that the items are all in a 5-item wide grid, which lets the browser easily take care of the details on how to lay it out for you.

Sounds interesting.

What do you mean by this?

How do you make a 266px X 174px grid?

You give the container that size, and the grid makes everything fit within it.

I think that would be crazy to do.

Why do you think it would be crazy?

How would you make something like that?

Here’s a tutorial https://scrimba.com/p/pWqLHa/cg92LA6

The full course is at Learn CSS Grid for Free

I do not think it would make logical sense to do a grid.

No? That 5x3 grid of links looks remarkably grid-like.

2 Likes

Let me get this straight, you’re suggesting I turn this into a grid?

It doesn’t have to be a grid - just getting rid of those nth-of-type styles would be progress in its own right.

Do you mind if I take a look at that?

Sure, I disabled the cover on this one.

Or, I could’ve just removed the javascript:

I’m stuck here: