Cain Nuke
Cain Nuke

Reputation: 3083

CSS select only elements that dont have a class starting with this

Hi,

I have this html code:

<ul>
 <li>
  <a href="#">Locations</a>
  <ul class="submenu1">
   <li><a href="https://url.com">London</a></li>
   <li><a href="https://url.com">York</a></li>
  </ul>
 </li>
 <li>
  <a href="#">About</a>
  <ul class="submenu2">
   <li><a href="https://url.com">Site</a></li>
   <li><a href="https://url.com">Contact</a></li>
  </ul>
 </li>
</ul>

I want to select all the a elements EXCEPT the ones that are children to the submenu class elements.

I tried like this:

ul li a:not([class^="submenu"] a) {background-color:darkkhaki;}

but it wont work. Whats the right selector for this case?

Thank you.

Upvotes: 0

Views: 67

Answers (2)

Geoffrey C.
Geoffrey C.

Reputation: 231

Hello dear CSS friend!

In other words, taking your example, you want to select "Locations" and "About" links but not the others.

(Kind of) dirty one

The easier to understand solution is to apply styles to all a then remove the styles to the others.

li > a {
     /* Styles you want to apply */
}

[class^="submenu"] a {
    /* Remove styles here */
}

It's always dirty to place styles then remove them, because it's less maintainable and a bit more heavy. But it will do the job.

Nicer solution

In your case, the submenu links are the only child of your li elements. That's why I would try to target the links that are not only child of your list item to style those, like that.

li a:not(:only-child) {
    /* Your styles here */
}

For more information on :only-child pseudo class, I leave you with some reading :) https://developer.mozilla.org/fr/docs/Web/CSS/:only-child

Don't hesitate if you have question, and have fun!

Upvotes: 2

DanyAlejandro
DanyAlejandro

Reputation: 1468

Option 1:

This will work:

ul li a {
  background-color: darkkhaki;
}
ul ul li a {
  background-color: transparent;
}

Just reset the styles on the elements you don't want styled.

Option 2:

If you have a container, for example a <div id="menu"> you can do:

#menu > ul > li > a {
  background-color: darkkhaki;
}

Upvotes: -1

Related Questions