Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply CSS to all but last element?

Tags:

I've got the following html:

<ul class="menu">
  <li><a>list item 1</a></li>
  <li><a>list item 2</a></li>
  ...
  <li><a>list item 5</a></li>
</ul>

I want to apply a border to all the <a> elements except the last one.

I've been trying this:

.menu a {   
  border-right: 1px dotted #ccc;
}
.menu a:last-of-type {
  border-right: none;
}

but I end up with a border on none of the elements, I guess because the <a> in each case is the last of type.

How can I do this? I'd prefer to use only CSS if possible, and I'd like IE9 compatibility if possible.

like image 449
Richard Avatar asked Mar 28 '16 18:03

Richard


People also ask

How do you select all but the last element in CSS?

When designing and developing web applications, sometimes we need to select all the child elements of an element except the last element. To select all the children of an element except the last child, use :not and :last-child pseudo classes.

How do you not get the last element in CSS?

The :not() selector excludes the element passed to it from selection. The :last-child selector selects the last child.

How do I apply CSS to all elements except one?

Approach: Use the :not(selector), also known as negation pseudo-class which takes a simple selector as an argument and allows you to style all the elements except the element specified by the selector.

How do I get the last element in CSS?

The :last-child selector allows you to target the last element directly inside its containing element. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.


1 Answers

Change:

.menu a:last-of-type {
  border-right: none;
}

to:

.menu li:last-of-type a {
  border-right: none;
}

.menu a {   
  border-right: 1px dotted #ccc;
}
.menu li:last-of-type a {
  border-right: none;
}
<ul class="menu">
  <li><a>list item 1</a></li>
  <li><a>list item 2</a></li>
  <li><a>list item 3</a></li>
  <li><a>list item 4</a></li>
  <li><a>list item 5</a></li>
</ul>

As you surmised, the rule you were using was targeting every a because it was the last child within each li. Just move the :last-of-type to the li instead.

like image 131
j08691 Avatar answered Sep 19 '22 15:09

j08691