Marcel
Marcel

Reputation: 15740

Using css only, how to select html elements inside a div/class but exclude some nested div/classes

Here is a simplified page struture, where I want to select all images inside the "page"-div and enclosed elements, but not those that are in either "keepoffa" or "keepoffb".

<!DOCTYPE html>
<html lang="en">
  <body>
    <div class="page">
       <img/> <!-- OK -->
       <div class="keepoffa">
          <img/> <!-- never take this-->
       </div>
       <div class="keepoffb">
          <img/> <!-- never take this-->
       </div>
       <img/> <!-- OK -->
       <div class="subpage">
           <img/> <!-- OK -->
           <ul>
               <li>
                   <img/> <!-- OK -->
               </li>
           </ul>
       </div>
       <ul>
           <li>
               <img/> <!-- OK -->
           </li>
       </ul>
    <div>
  </body>
</html>

Here's what I have thought:

.page img:not(.keepoffa):not(.keepoffb) {
    max-width: 300px;        
}

But the unwanted divs are not excluded.

How to effectively select the images but exclude the images inside those unwanted divs? CSS-only required.

Upvotes: 1

Views: 105

Answers (3)

Ferrmolina
Ferrmolina

Reputation: 2771

Use > operator to select the child of .page div. And .subpage img to the another image

.page > img,
.subpage img{
  border: 1px solid red;
}
  
  <div class="page">
       <img src="http://placehold.it/100x100"/> <!-- OK -->
       <div class="keepoffa">
          <img src="http://placehold.it/100x100"/> <!-- never take this-->
       </div>
       <div class="keepoffb">
          <img src="http://placehold.it/100x100"/> <!-- never take this-->
       </div>
       <img src="http://placehold.it/100x100"/> <!-- OK -->
       <div class="subpage">
          <img src="http://placehold.it/100x100"/> <!-- OK -->
       </div>
<div>

Upvotes: 1

Arman Ozak
Arman Ozak

Reputation: 2344

Try this:

.page>img,
.page div:not(.keepoffa):not(.keepoffb) img {
    max-width: 300px;        
}

Upvotes: 0

General_Twyckenham
General_Twyckenham

Reputation: 2259

You can't use two pseudo-selectors simultaneously (and your selectors weren't correct anyway).

EDIT: Probably the easiest way is something like this:

    .page img {
        max-width: 300px;
    }

    .keepoffa img, .keepoffb img {
        max-width: initial;
    }

Upvotes: 0

Related Questions