-9999px...meh: Better image replacement
- All credit for this goes to Scott Kellum via the Jeffrey Zeldman
-9999px works like a charm. But the browser has to do work it actually draws the box offscreen. Not so hot for devices, especially when the screen is only about 320px.
Here is one that takes less work for the browser:
.hide-text {
text-indent: 100%;
white-space: nowrap;
overflow: hidden;
}
It will only draw the box as big as the container it is in.
Written by Peter Peterson
Related protips
9 Responses
I'd say the HTML5Boilerplate version is better and supposedly thoroughly tested (large community).
.ir {
background-color: transparent;
border: 0;
overflow: hidden;
/* IE 6/7 fallback */
*text-indent: -9999px;
}
.ir:before {
content: "";
display: block;
width: 0;
height: 100%;
}
From: https://github.com/h5bp/html5-boilerplate/blob/master/css/main.css#L120-133
I've always wandering why not simply font-size: 0px;
?
@francisc Nice action! Haven't messed around with H5BP in a few months. Can't go wrong with such a large community. Thanks for the tip!
@ipetepete Yeah, that's what I thought. They refined this a lot over time. It looks nothing like it did at the start of the year.
Thanks as well.
@hauleth It's because of browser quirks. Not all hide the text, some show it at the default size, others at a very-small-but-still-visible size.
Plus there is/was a SEO score hit when you use(d) this.
@hauleth Using font-size: 0px will affect SEO, and may actually "hurt" your index. This technique was used by cheaters inserting keywords on irrelevant parts of their pages to increase their ranking. I'm no expert, but I hear its bad-mojo
Just a heads up: this method adds scroll bars to elements which are floated left and doesn't work at all for elements which are floated right.
What's wrong with using display:none; to hide elements?
I just wanted to point out the white-space: nowrap
line; it's important because otherwise you'll see lines two and beyond. It (and overflow: hidden
, of course) are the secret sauce here.
@hauleth: in addition to being bad for SEO (see @ipetepete's comment) it's also difficult when you're using em-based units (which is really handy for fluid layouts). width: 24em
will yield a zero-pixel box.
There's the question of whether any text-hiding technique (including this one) triggers Google's black-hat SEO sniffing. Some techniques, though (such as font-size: 0
) are definite no-nos.
@wildlyinaccurate: I tested your statement out, and I'm not getting the same results. Perhaps you're thinking about overflow: auto
and overflow: scroll
?
@htbaa: This technique is for keeping the element (for styling with a background image) but hiding its text. Useful when you want fancy text that you could never duplicate in CSS; you create an image in your image editing program and apply it as a background image to stand in for the plain text.