Mohamed Hussain
Mohamed Hussain

Reputation: 7703

How to hide alt text using CSS when the image is not present?

Is it possible to hide the alt text using CSS in all the browsers,

I tried with color:transparent, it is working in all browsers except IE.

Is it possible to do it in IE using CSS?. Thanks in advance for any help.

Upvotes: 26

Views: 49893

Answers (9)

iorgu
iorgu

Reputation: 3009

This worked:

img {
  color: rgba(0, 0, 0, 0) !important;
}
<img src="example.jpg" alt="text you don't want to show for those who can see, but make it visible for screen readers" />

transparent neither worked for me.

Upvotes: 0

Co ti
Co ti

Reputation: 144

I think this is a best solution:

img {
  text-indent: -100vw;
  overflow: hidden;
}

An empty image is centered and alt text is not displayed. Also it does not overflow over other images.

Upvotes: 0

This seems to work for me. Just add it to your img styles:

text-indent: -100%;
overflow: hidden;

Upvotes: 1

Raynal Gobel
Raynal Gobel

Reputation: 1080

The kellum method:

.hide-text {
    text-indent: 100%;
    white-space: nowrap;
    overflow: hidden;
}

Also don't have the performance drawback of -9999px method where browser draw a box with size of 9999px.

Further explanation: replacing-the-9999px-hack-new-image-replacement

Upvotes: 18

TobinWebsites.com
TobinWebsites.com

Reputation: 231

How about using font-size: 0? It works in hiding alt text before image loads or if image src URL is not available.

Upvotes: 23

Martin Brandl
Martin Brandl

Reputation: 58931

You could also use the onerror callback to set the display property to none:

<img src="images/test.txt" onerror="this.style.display='none';">

Upvotes: 5

Gaurav Aggarwal
Gaurav Aggarwal

Reputation: 10187

You can use text-indent:-9999px

HTML

<img src="images/test.jpg" alt="alternative">

CSS

img{
  text-indent:-9999px
}

Demo

Upvotes: 7

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

Instead of using color:transparent; use display:none;.

But you should not use this technique.

As @Quentin said in the comment:

If the text isn't good enough for humans then it isn't good enough for search engines.

You should not hide the alt text. Google knows this only used for SEO purpose and nothing important and will penalize for such. And you may be blacklisted on Google Search Engine.

So, don't use them just for SEO purpose.

Upvotes: 2

Murad Hasan
Murad Hasan

Reputation: 9583

Use text-indent: -9999px; and display: none.

fiddle link

HTML

<h1 class="technique-four">
  <a href="#">
    <img src="images/header-image.jpg" alt="CSS-Tricks" />
  </a>
</h1>

CSS:

h1.technique-four {
    width: 350px; height: 75px;
    background: url("images/header-image.jpg");
    text-indent: -9999px;
    display: none;
}

Upvotes: 0

Related Questions