Smashing Magazine - we smash you with the information that will make your life easier. really.
[Ask SM: CSS] Equal Spacing, CSS Font Replacement
This is our fourth installment of Ask SM, featuring reader questions about Web design, focusing on HTML, CSS and JavaScript. In this post we’ll cover how you can distribute the horizontal space between elements evenly, how you can achieve maximum sides on images; you’ll also learn best practices for CSS font replacement and answers to a couple of quickfire questions. If you have a question about CSS or JavaScript, feel free to reach me (Chris Coyier) via one of these methods:
- Send an email to ask [at] smashingmagazine [dot] com with your question.
- Post your question in our forum.
- Or, if you have a quick question, just tweet us @smashingmag or @chriscoyier.
Please note: I will do what I can to answer questions, but I will certainly not be able to answer all of them. However, I hope you use the forums to post questions because that gives you the best opportunity to get help from the community.
Distributing the horizontal space between elements evenly
Antoine Nicolas writes:
Do you know how to perfectly and dynamically distribute objects horizontally in a container using CSS?
Hi Antoine, this is a classic example of something that is fairly difficult to do in CSS but probably shouldn’t be. I have approached this problem in a number of different ways in the past. I have revisited it a little now, and I’ll present what I believe is the best solution here.
![Equidistant in [Ask SM: CSS] Equal Spacing, CSS Font Replacement](http://media.smashingmagazine.com/images/ask-sm-css/equidistant.png)
Let’s review the specific goals:
- The left-most object is left-aligned with its parent element.
- The right-most object is right-aligned with its parent element.
- All objects are equidistant from each other at all times.
- The objects will stop short of overlapping each other as the browser window narrows (ideally).
- The objects will not wrap down as the browser window narrows (ideally).
- The technique will work in a fluid-width environment, even one that is centered.
The theory is that the first object will be left-aligned, and the rest of the objects will be right-aligned inside equal-sized boxes that take up the rest of the space. Here is an illustration of what I mean:
![Floatytechnqiue in [Ask SM: CSS] Equal Spacing, CSS Font Replacement](http://media.smashingmagazine.com/images/ask-sm-css/floatytechnqiue.png)
The HTML markup:
<div id="row"> <img src="images/shape-red.png"> <div id="movers-row"> <div><img src="images/shape-green.png"></div> <div><img src="images/shape-yellow.png"></div> <div><img src="images/shape-blue.png"></div> </div> </div>
The CSS:
#row {
min-width: 480px;
}
#movers-row {
margin: -120px 0 0 120px;
}
#movers-row div {
width: 33.3%;
float: left;
min-width: 120px;
}
#movers-row div img {
float: right;
}And here is a live demo.
Maximum Sides on Images
![Maxside in [Ask SM: CSS] Equal Spacing, CSS Font Replacement](http://media.smashingmagazine.com/images/ask-sm-css/maxside.png)
J.J. Sylvia IV writes:
Is there a way to determine the dimensions of an image being displayed and change the <img width=”" /> setting based on the overall width? Sometimes I have images with a really large height, and I need them to be displayed with a much smaller width than other images.
I talked with J.J. a little more about this to clarify the problem. The problem actually relates to height: you have a lot of images, and all of them have different dimensions. You could set a max-width to make sure they keep their ratio and all get squeezed to the right width, but that leaves “jagged” heights. In other words, when you control only the width, you get the benefit of maintaining the image ratio, but you cannot control the height and may end up with very tall images screwing up your layout.
So how do you control both the height and width while maintaining ratio? We will need to lean on some JavaScript because we have to perform some calculations. As I happen to be a jQuery guy, we’ll use that. jQuery is a good choice here anyway, though, because we need to target every single image on the page and do stuff do it, and jQuery makes that very easy and rips through the job.
The best route is to turn this into a plug-in, which will make it a very easy call, as well as allow it to be chained and all that good stuff. We’ll call it “maxSide”. It looks at each element it calls on and figures out which dimension is larger. If it’s the width, it sets the width to the “maxSide” (with the pixel setting passed in). If it’s the height, it sets the height to the “maxSide”.
Here is the plug-in:
(function($) {
$.fn.maxSide = function(settings) {
// if no paramaters supplied...
settings = $.extend({
maxSide: 100
}, settings);
return this.each(function() {
var maximum = settings.maxSide;
var thing = $(this);
var thewidth = thing.width();
var theheight = thing.height();
if (thewidth >= theheight) {
if (thewidth >= maximum) {
thing.attr({
width: maximum
});
}
}
if (theheight >= thewidth) {
if (theheight >= maximum) {
thing.attr({
height: maximum
});
}
}
});
};
})(jQuery);Since we intend to call this plug-in with images, we need to make sure all of the images have loaded first. So, instead of calling it when the DOM is ready, like you see in most jQuery, we need to call it once the window has loaded.
$(window).bind("load", function() {
$("img").maxSide({ maxSide: "100" });
});;This may cause some unsightly flashes of large images… C’est la vie. If it’s really really awful, you may wish to hide the images with CSS and only reveal them (with jQuery) after the plug-in has run.
Here is a live example of this plug-in at work.
CSS Font Replacement
@juliuskoroll writes:
I would like to hear font replacement via CSS explained by you guys.
Hi Julius, you got it! We all know we can include images on pages just by including an image tag like this: <img src=”http://media.smashingmagazine.com/images/ask-sm-css/…” alt=”…” />. That image can be anything. It can be a logo, a picture of a nice cup of tea, a puppy or even a line of text in a custom font acting as a header. If we want to have headers with nice custom fonts on our website, one option available to us is to just insert them in the page with <img .. /> tags. While this solution has no visual penalty, it has problems. The proper HTML tag to use for headers is the header tag (e.g. <h1>, <h2>, etc). This is best for accessibility as well as SEO (search engine optimization).
You may also be aware that CSS allows us to place background images on elements. This is what gives us the power to have the best of both worlds. We can use a proper header tag, but also use an image. The problem now is that the text within the header tag is sitting right on top of the image. We need to somehow hide the text so that only the image is visible. As it turns out, there are quite a few different ways to do this, and each comes with its own theory. I once did some reasearch on this subject and came up with Nine Techniques for CSS Image Replacement.
![Fontreplacement in [Ask SM: CSS] Equal Spacing, CSS Font Replacement](http://media.smashingmagazine.com/images/ask-sm-css/fontreplacement.png)
The most popular method, in my experience, is known as the Phark method. While it may not be the absolute best method, it works and is very easy to understand.
HTML:
<h1 class="replace"> Smashing Magazine </h1>
CSS:
h1.replace {
width: 350px; height: 75px;
background: url("images/header-image.jpg");
text-indent: -9999px;
}Quickfire Questions!
Here are a few questions I wrote down from random sources. Like most Web design questions, they could be answered with a book. But instead, I’ll answer them with a single sentence (or two) and a link!
1) Is there a way to make drop-down menus without JavaScript for IE 6?
Yes, there is, perhaps most famously done by Stu Nicholls of CSSplay, with his ULTIMATE CSS only drop-down menu.
2) Is there a way to get PNG transparency without JavaScript or HTC solution in IE 6?
To clarify, this means alpha transparency. Regular ol’ transparency (think GIFs) works fine with PNGs without any hacks, even in IE 6. Most PNG hacks do indeed use JavaScript or HTC. The root of these techniques is to apply a proprietary CSS “filter” called “AlphaImageLoader” through the “behavior” attribute in CSS. Some of these fixes are incredibly easy to implement, but if you want to avoid them all together, it is a little-known fact that Fireworks can save PNG-8’s with alpha transparency.
3) Is there a way to remove the “Click to activate this control” message for some versions of IE with Flash content?
Yep, inserting Flash objects on your page with SWFObject clears up this issue.
4) Is there a way to have alternate sidebars in WordPress?
Sure, if you have a special page template that you want to display a different sidebar other than your regular one, you can do that. The default WordPress function that calls the sidebar looks like this:
<?php get_sidebar(); ?>
It may look like a magical WordPress function, and I suppose it is, but all it does is grab the sidebar.php file from your theme and plop it in. That’s it. So, instead, duplicate that sidebar.php file, call it something like sidebar-alternate.php and call it from your special page template like this:
<?php include (TEMPLATEPATH . '/sidebar-alternate.php'); ?>
That does about the same exact thing. You can use that same bit of code to include any file from your theme folder.
5) Can you style “alt” tags using CSS?
The “alt” attribute for elements is only ever displayed if (for whatever reason) the element to which it is applied cannot be rendered. This is most common for <img .. /> elements, but also for <area> elements and optionally for inputs (because they can sometimes be images). So, the only reason you’d ever see “alt text” is when an image link is broken or you are browsing the Web intentionally without images (e.g. using accessibility software).
The answer is yes, you can style “alt” text CSS. Simply apply text styling CSS attributes to whatever element it is. I think this is a rather clever idea actually. Images are very eye-catching on Web pages, so when an image is unavailable, why not replace it with very descriptive and eye-catching text.
It seems a little weird, but:
img {
color: red;
font: italic 200% Georgia, Serif;
}This will sure make that “alt” text pop!
(al)
I create websites and help others create better websites through writing and speaking. I consider myself a lucky man for getting to work in such a fun and rewarding field.
- 70 Comments
- 1
- 2March 23rd, 2009 12:12 am
Hmm, not bad, not bad. Thanks.
- 3March 23rd, 2009 12:40 am
Nice Post !! May be I also came up with some questions and answers too.
DKumar M.
- 4March 23rd, 2009 12:40 am
Very useful information, just in time for me. Thanks!
- 5March 23rd, 2009 12:44 am
There’s actually another way to call alternate sidebars (or headers and footers) in WP. Name your new sidebar sidebar-new.php and then you can call it with <?php get_sidebar(’new’); ?> ;)
- 6March 23rd, 2009 12:45 am
Very helpful! :) Keep’em coming
- 7March 23rd, 2009 12:48 am
great post! thanks. Good that you guys came back soon! :)
- 8March 23rd, 2009 12:52 am
Probably the worst way to distribute horizontal space between elements evenly.
- 9March 23rd, 2009 1:11 am
Thank God IE8 supports CSS Tables, soon many of the hacks we use today will be a piece of cake :)
- 10March 23rd, 2009 1:11 am
Very useful information, also clear answers!
- 11March 23rd, 2009 1:37 am
You say famously, but CSSplay’s drop down menu’s are notoriously poorly implemented, using loads of conditional hacks all over the place instead of CSS to get them to work. I wouldn’t have given that as an acceptable solution to the original question, personally.
- 12March 23rd, 2009 2:23 am
Already applied some of this CSS tricks on some of my projects. the main clue is to understand the box model representation including margin, padding and border and to keep/distribute everything under 100%. do the calculation first then design.
- 13March 23rd, 2009 2:28 am
thanks!
the negative text-indent is perfect for my current projects usability issues. - 14March 23rd, 2009 2:38 am
I too would love to see an article on “font replacement” but wasn’t the reply to that more about “image replacement”. I would have thought font replacement would refer to replacing a font while still keeping the text as real text.
What are your thoughts on Sifr, and other alternatives for font replacement?
http://www.smashingmagazine.com/2009/01/27/css-typographic-tools-and-techniques/ only touches on it. Would love to see an in depth smashing styled article on font replacement. I personally find sifr to be a bit of a nightmare. I won’t be using anything liek it until there’s a bulletproof, easily scalable font repalcement. - 15March 23rd, 2009 2:41 am
wow, nice article, i like it, thanks sm
- 16March 23rd, 2009 2:45 am
CSS Font Replacement: what about SEO?
is this a bad seach engine ranking tecnique?
I have read (I can’t remember where) that is a DO NOT DO for gaining a good ranking position in search engines. Am I wrong? - 17March 23rd, 2009 2:46 am
WP lets you use multiple sidebar with the
get_sidebarfunction since v2.5:
http://codex.wordpress.org/Include_Tags#The_Sidebar_Template - 18March 23rd, 2009 3:36 am
To still utilize seo on font replacement you can add span tag with a display none with copy describing the image inside the header tag in your html if that makes any sense. You can google it. It isnt the most proper way to do it but it works.
- 19March 23rd, 2009 3:45 am
I think the SEO should be fine because the text is still there, it is just moved out of the window, but if it is in the code SEO will pick it up still.
If you use an img tag instead of plain text and CSS then you will get the issue you are presenting here. Also for image you always have the alt attribute I guess, but the CSS approach is best.
To be honest with you I personally hate CSS font replacement or anything that have embedded text. But that’s a personal preference, I like to be able to select any text present on a website if I do need to copy/paste anything.
Top of that pure text is best for accessibility tools :)
- 20March 23rd, 2009 5:37 am
The “alt” attribute for elements is only ever displayed if (for whatever reason) the element to which it is applied cannot be rendered.
Apart from – surprise, surprise – Internet Explorer, which has a bug whereby alt text is displayed as a tooltip (behaviour that should be reserved for the title attribute).
- 21March 23rd, 2009 5:44 am
Good stuff! Thanks!
- 22March 23rd, 2009 5:47 am
Font replacement is key. A good SEO technique.
- 23March 23rd, 2009 5:48 am
Here is a proper image replacement method I recommend (works well on links too under IE) :
display: block;
width: WIDTHpx;
height: 0;
font-size: 1em;
padding-top: HEIGHTpx;
text-indent: -2000px;
overflow: hidden;
background: url(’your image’) no-repeat; - 24March 23rd, 2009 5:51 am
hmm.. I’m not a SEO expert but here http://www.google.com/support/webmasters/bin/answer.py?answer=66353
there is the google guidelines on hiding text and googling you can find other resources about this topic
http://www.google.it/search?q=css+image+replacement+seoIt’s still vague..
- 25March 23rd, 2009 5:56 am
What the heck? PNG-8 alpha transparency in IE6 with no hacks? No one ever told me! Thank you Smashing Magazine!!!!
- 26March 23rd, 2009 5:57 am
Just a question regarding the negative text-indentation.
I have heard search engines could take it like black hat technique and could penalty your site since you are hiding the text. What do you think about it?
- 27March 23rd, 2009 6:03 am
The equidistant images technique is indeed hard to achieve, I had never thought about this one, thanks!
- 28March 23rd, 2009 6:30 am
@Razvan Pavel: I’d love to hear other ways to do this if you have some. I explored a lot of different ways to accomplish this and what I have presented here is literally the best way I’ve found that accomplishes all the goals.
@strexy: Regarding SEO, image replacement isn’t a problem, if used honestly. The text is still present so search bots can read it, and it’s tagged properly as a header. Even Google’s Matt Cutts has said it’s OK.
@Johnny: Yeah! Who knew? I’d love to try it myself but as far I know you need Fireworks to do it which personally I don’t have.
@Sergio Ordoñez: Same deal here as I said to strexy above, if you use it responsibly I do not believe you will ever be penalized for using negative text indent. If you are trying to do something nasty and specifically “game” the system, do it at your own risk.
- 29March 23rd, 2009 6:40 am
Thanks for the tips. I hate how difficult it can be to lay a page out with CSS when I know I can do it in five minutes with tables. I haven’t used tables for layout in a while but some of the CSS I have to use drives me mad.
The Alpha Channels on PNG-8 was new to me – definitely has it’s place for certain images. Thanks for sharing.
- 30March 23rd, 2009 7:09 am
Nice article. I really like the alt styling idea. :)
- 31March 23rd, 2009 7:12 am
Re: the Fireworks PNG8 alpha trick.
I just recently found out about this too. It was one of those “tiny angels singing in my head” moments. One caveat: any semi-transparent elements (like the oh so popular drop-shadows) will NOT appear in IE6. Only the fully opaque pixels will be shown. Any pixel with partial alpha will become fully transparent.
- 32March 23rd, 2009 7:29 am
I’ll second what @atomicnoggin says – the Fireworks PNG8 isn’t quite what it sounds – you can’t achieve semi-transparency with it, and can’t anti-alias edges, only control which pixels are visible and which aren’t. Still, it’s better than having a white box around everything…
- 33March 23rd, 2009 7:32 am
@Johnny:
The Fireworks PNG technique works well if your images are composed of solid colors. Images with subtle gradients come out riddled with blocky color bars. So I highly recommend pulling in your PNG8s with a style sheet specifically for IE6.
- 34March 23rd, 2009 7:38 am
I love that even Chris fell foul of the ‘turn all link text into “Link”‘ filter! ;-)
- 35March 23rd, 2009 7:49 am
What if the elements that I need to distribute are not of equal width? I currently use dynamic right margins calculated by Javascript to achieve the same effect, but it’s not the most elegant solution.
- 36March 23rd, 2009 8:32 am
I don’t think you answered the question about “distributing the horizontal space between elements evenly.” The questioner mentioned objects (I think they meant text) and you showed how to distribute images. I would also like to distribute the text evenly in my blog posts. Please help. Thanks
- 37March 23rd, 2009 8:33 am
Great article Chris, some cool things I didn’t know about here.
- 38March 23rd, 2009 8:33 am
To your equal horizontal distance article.
Really nice stuff. thank you man.
but the demo will look much better with
#page-wrap { min-width:540px; }
(540 = 30 padding left + 480 content + 30 padding right) - 39March 23rd, 2009 8:54 am
Very useful informations, Thanks!
- 40March 23rd, 2009 10:12 am
Thanks a lot, nice article as usual !
- 41March 23rd, 2009 10:23 am
in reference to “Can you style “alt” tags using CSS?” Styling Alt tags is great if your working with email, as the Alt tags will show up by default and until the images have downloaded.
Unfortunately you can’t style them with a CSS style-sheet, but instead have to use In-Line styles. I usually us it for font-family, color, font-size, font-weight, etc…
- 42March 23rd, 2009 10:29 am
@Can Berk Güder: JavaScript is definitely another way to go for equidistant stuff. I’d love to see your code for that. My solution above is definitely equal-width-only.
- 43March 23rd, 2009 10:59 am
I’d recommend using JQuery or Prototype for this stuff.
Here’s a snippet for JQuery:
$(document).ready(function(){
$('#YourId').innerHTML = 'your_image_url';
}
- 44March 23rd, 2009 11:05 am
@ Chris Coyier: common sense tell me the same, you can use negative text-indent to hide text if your purpose is legitime. The issue is if the search engine can discriminate efficiently when its a legitimate use or not… but going further, your concept of “legitimate” could not macht the search engine concept.
From the article you linked I couldnt say its 100% sure and safe:
“…CSS Image Replacement in theory is a legitimate reason to hide text, but it is not always clear if Google and the other search engines are fine with it…
…So according to Matt Cutts it depends on how you use the technique. He does mention that it can be a reason to get your website flagged for spam though.”
I think even Matt Cutts is not sure, he dont position himself clearly.
- 45March 23rd, 2009 11:53 am
ROTFL these are miserable funny :/ Why boring people with such primitive noob solutions?! Anyone thinks serious must know the above at first… and forget it after a second, stepping beyond. So SM is a professional magazine or a how-to collection for dummies?
- 46March 23rd, 2009 12:59 pm
I only wish I could be as amazingly talented and knowledgeable as Razvan Pavel and Mayer. If only they would deign to bless the rest of us with their wisdom instead of just making disparaging comments!
- 47March 23rd, 2009 5:49 pm
Nice post. I would just like to add that you could also space out elements evenly from one another if you were to use a grid. There was no mention of a grid anywhere on this article. Either I have got the gist of the equal space problem wrong or perhaps grids were just overlooked. Is this the case?
- 48March 23rd, 2009 8:42 pm
the “alt” style thing is cool.. never gave it a thought before.. but definitely worth doing…
- 49March 24th, 2009 3:05 am
hello, I have googled a little about SEO and IMAGE REPLACEMENT and I still think that it shouldn’t be used in websites that need a good ranking position on search engines. Is there anyone who can post any links to confute this thesis?
- 50March 24th, 2009 7:59 am
@strexy: its a gray area, you wont find anything confirming anything.
Common sense tell me it should be safe since its widely used for legitimate purposes, but who knows if the search engine can discriminate your intention.
- 51March 24th, 2009 1:07 pm
Check out Cufon for font replacement: http://cufon.shoqolate.com/generate/. Requires JS, but works well and is still configurable with CSS.
- 52March 24th, 2009 5:25 pm
ow… i’ll try this one..
simple but awesome :) - 53March 25th, 2009 5:37 am
I am working with image replacement and wondering the best way to do it with links. For example, using a logo or name as h1 and being a link back to your home page. Especially in Wordpress (I have followed Chris’ ‘Designing for WP’ video series, Thank Chris!). I am styling the link inside the h1 with id “logo”.
Here’s what I’ve got. Any thoughts?
jellyFaceCSS:
#logo {
width: WIDTHpx;
height: HEIGHTpx;
background-image: url(LOGO.png);
background-repeat: no-repeat;
display: block;
text-indent: -9999px;
} - 54March 31st, 2009 2:31 pm
Here is googles take on image replacement:
http://mezzoblue.com/archives/2008/05/05/image_replac/
short answer – it’s fine
also since I’m throwing my 2 cents in, the best image/font replacement technique is Gilder/Levin because phark fails under the images off but css on scenario.
see: http://www.mezzoblue.com/tests/revised-image-replacement/ - 55May 22nd, 2009 8:22 pm
Good stuff! Thanks!
- 56June 1st, 2009 11:06 pm
The tips are all great. Thanks for the image replacement ideas.
Also a shameless plug for my open source project, but for those of us in Linux, BSD and Mac land (and Windows users that don’t want to play with GUI’s) you can convert pngs to png-8 with pngnq. Check it on sourceforge.
Someday IE will get png support right. - 57June 22nd, 2009 8:28 am
3HKAeT comment6 ,
- 00
There are no trackbacks at this time. If you are interested in leaving a trackback, please use this URL.
Leave a Comment
Make sure you enter the * required information where indicated. Please also rate the article as it will help us decide future content and posts. Comments are moderated – and rel="nofollow" is in use. Please no link dropping, no keywords or domains as names; do not spam, and do not advertise!
- Magazine RSS Feed
177,918 readers - Follow us on Twitter
83,673 followers
Interact
Popular
- 100 Wordpress Themes
- Photoshop Tutorials
- Fantastic Wallpapers
- 40+ Excellent Freefonts
- Dual-Screen Wallpapers
- Wordpress Themes for 2009
- Illustrator Tutorials
- Incredible Free Icon Sets
- High-Quality Free Fonts
- 30 Scripts For Galleries
- Photoshop Text Effects
- Useful Icon Sets
- Web Design Trends
- iPhone Wallpapers
- Before Launching a Website
- CSS Layouts And Templates
- Photoshop Actions
- Stunning Pictures and Photos
- Fantastic HDR Pictures
- Logo Design Tutorials
- Free Design Templates
- 10 Mistakes In Logo Design
- Photoshop Custom Shapes
- 40 Creative Design Layouts
- 8 Layout Solutions
- 53 CSS Techniques
- Photography Techniques
- Black & White Photography
- Styling Design Elements
- CSS-Based Forms
- 50 jQuery Techniques
- 50 Portfolio Websites
- 50 CSS Techniques
- Creative Logo Designs
- Desktop Wallpapers
- 25 Open Source Mac Apps
- 50 Free Icon Sets
- Glassical: A Free WordPress Theme - http://bit.ly/19EvYr
- Please nominate Smashing Magazine for Best Online Magazine in the 2009 Open Web Awards - http://bit.ly/10ynWA
- Mega Drop Down Menus with CSS & jQuery - http://bit.ly/24novl
- Join us on the Smashing Magazine's Official Facebook Page - http://bit.ly/18ebRT
- #followfriday @inspiredmag @designerdepot @DesignMagTweets @inspirationbit @Colorburned @buysellads @TheCoolHunter @behoff
- New format on @smashingmag: The Beauty of London in Design - http://bit.ly/1Hkju8
- Unbelievable: Ponte City Tower in Johannesburg - http://bit.ly/Iv2k5 - When modern architecture isn't beautiful.


Wow nice article. May try some of this :)