skip to Main Content

How would I use CSS to style all elements that are not images? I tried using

body:not(img) {
    filter: grayscale(1);
}

but this does not work.

2

Answers


  1. Doing :not on the body will target elements directly on the body.

    What you’re after is something like

    body *:not(img) {}
    

    This targets all elements ‘*’ where the element is not the img tag.

    Although you may need to tweak this, as doing this might also interfere with your images depending on things overlapping (such as parent divs of the images).

    Login or Signup to reply.
  2. A greyscale filter on any element will apply to all its contents. So your selector not only needs to exclude images, it also needs to exclude elements which have an image descendant. This is the selector you need:

    :not(img, :has(img))
    

    Here is a small snippet to demonstrate this working. Images, whether wrapped or not, remain in colour, while the rest of the document becomes greyscale. Tested in Chrome, Safari and Firefox on Mac.

    .p1 {
      color: red;
    }
    
    .p2 {
      background: linear-gradient(90deg, rgba(110,229,255,1) 0%, rgba(192,118,255,1) 100%);
    }
    
    :not(img, :has(img)) {
      filter: grayscale(1);
    }
    <p>This is black</p>
    <p class="p1">This is red</p>
    <p class="p2">This has a blue gradient background</p>
    <img src="http://picsum.photos/id/840/120">
    <img src="http://picsum.photos/id/845/120">
    <div>
      <img src="http://picsum.photos/id/840/120">
      <img src="http://picsum.photos/id/845/120">
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search