CSS condition for when you don’t have SRC in the image

Asked

Viewed 341 times

5

I need that when an image does not have the attribute src, css automatically recognizes this and hides that element with display:none

Which selector should I use to do this?

Example:

 <img src="tem_imagem" class="image" />
 <img class="image" />

3 answers

5


img[src=""], img:not([src]) {
  display: none;
}
<img src="">
<img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
<img class="teste" border="1">

  • But if there really is no src attribute, it will work?

  • Yes, it will. I’ll put it on the snippet.

  • 1

    I think in the case of "no src" it doesn’t work. If you put a class in this image by default and leave a border for example, it will be displayed. I think to make the right answer would be .minha-imagem[src=""],.minha-imagem:not([src]). It just worked that way here.

2

Use a attribute selector, and the pseudo-class :not():

img {
  width: 150px;
  height: 150px;
}
.no-src {
  background-color: #00f;
}
.empty-src {
  background-color: #0f0;
}

img[src=""],
img:not([src]) {
  display: none;
}
<img class="no-src"/>
<img src="" class="empty-src"/>
<img src="http://placehold.it/150x150"/>

-2

Puts a None display on ALL your imgs and display block on those that have src:

img[src] {
    display: block;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.