1

I want to style an ul, but the first li and last li should have different styles than the ones between them.

I know the below code is probably very wrong, but can you see what i'm trying to do?

.menu li:hover:not(.menu li:nth-last-child(1)) { border:red solid 1px; }

The HTML is only basic, just want some CSS's styles I can use for any other menus.

<ul class="menu">
   <li>All</li><li>Refresh</li><li>Saved</li>
</ul>

So, how do I style the middle li's when the user hovers over them? I want to do this to avoid putting a border in the middle of each list item.

Martyn Ball
  • 4,679
  • 8
  • 56
  • 126

2 Answers2

3

First solution: custom styles for first and last elements

One way is to style every <li> element and then customize the first and the last ones. For this, :first-child and :last-child are your friends.

With HTML such as:

<ul class="menu">
    <li>All</li>
    <li>Refresh</li>
    <li>Something else</li>
    <li>Saved</li>
</ul>

and the following CSS:

.menu li:first-child { font-weight: bold; }
.menu li:last-child { font-style: italic; }

You'll obtain:

  • All
  • Refresh
  • Something else
  • Saved

Second solution: apply a style to element 2 to n-1

If you can't, for a reason, define a common style for all list elements, and customize it for the first and the last ones, you can use the :not keyword. .menu li:not(:first-child) will exclude the first element, and .menu li:not(:last-child)—the last one.

Multiple :not are combined this way:

element:not(selector1):not(selector2)

which means that your CSS becomes:

.menu li:not(:first-child):not(:last-child)

For example:

.menu li:not(:first-child):not(:last-child) { font-weight: bold; }

will produce:

  • All
  • Refresh
  • Something else
  • Saved
Community
  • 1
  • 1
Arseni Mourzenko
  • 50,338
  • 35
  • 112
  • 199
0

Try using a CSS selector. The code below will affect the first and last child of the parent (UL).

ul:first-child {
 Style attributes here
}

ul:last-child {
  Style attributes here
}

More info on CSS selectors here http://www.w3schools.com/cssref/css_selectors.asp

snowYetis
  • 1,517
  • 16
  • 28