[Ask SM: CSS] Equal Spacing, CSS Font Replacement

Advertisement

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:

  1. Send an email to ask [at] smashingmagazine [dot] com with your question.
  2. Post your question in our forum1.
  3. Or, if you have a quick question, just tweet us @smashingmag2 or @chriscoyier3.

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 past4. I have revisited it a little now, and I’ll present what I believe is the best solution here.

equal distance

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:

floaties

The HTML markup:

name="code"><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:

name="code">#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 demo5.

Maximum Sides on Images

max side

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:

name="code">(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.

name="code">$(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 example6 of this plug-in at work.

CSS Font Replacement

@juliuskoroll7 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://www.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 Replacement8.

font replacement

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:

name="code"><h1 class="replace">
	Smashing Magazine
</h1>

CSS:

name="code">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 menu9.

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 transparency10.

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 SWFObject11 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:

name="code">img {
   color: red;
   font: italic 200% Georgia, Serif;
}

This will sure make that “alt” text pop!

(al)

Footnotes

  1. 1 http://forum.smashingmagazine.com/viewtopic.php?f=10&t=272
  2. 2 http://twitter.com/smashingmag
  3. 3 http://twitter.com/chriscoyier
  4. 4 http://css-tricks.com/equidistant-objects-with-css/
  5. 5 http://css-tricks.com/examples/EquidistantObjectsSM/
  6. 6 http://css-tricks.com/examples/MaxSide/
  7. 7 http://twitter.com/juliuskoroll
  8. 8 http://css-tricks.com/nine-techniques-for-css-image-replacement/
  9. 9 http://www.cssplay.co.uk/menus/final_drop.html
  10. 10 http://www.brenelz.com/blog/2009/01/27/png-8-alpha-transparency-screencast/
  11. 11 http://code.google.com/p/swfobject/
CSS

↑ Back to topShare on Twitter

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.

Advertising
  1. 1

    Wow nice article. May try some of this :)

    0
  2. 2

    Hmm, not bad, not bad. Thanks.

    0
  3. 3

    Nice Post !! May be I also came up with some questions and answers too.

    DKumar M.

    0
  4. 4

    Very useful information, just in time for me. Thanks!

    0
  5. 5

    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’); ?> ;)

    0
  6. 6

    Very helpful! :) Keep’em coming

    0
  7. 7

    great post! thanks. Good that you guys came back soon! :)

    0
  8. 8

    Probably the worst way to distribute horizontal space between elements evenly.

    0
  9. 9

    Thank God IE8 supports CSS Tables, soon many of the hacks we use today will be a piece of cake :)

    0
  10. 10

    Very useful information, also clear answers!

    0
  11. 11

    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.

    1
  12. 12

    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.

    0
  13. 13

    thanks!
    the negative text-indent is perfect for my current projects usability issues.

    0
  14. 14

    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.

    1
  15. 15

    wow, nice article, i like it, thanks sm

    0
  16. 16

    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?

    0
  17. 17

    WP lets you use multiple sidebar with the get_sidebar function since v2.5:
    http://codex.wordpress.org/Include_Tags#The_Sidebar_Template

    0
  18. 18

    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.

    0
  19. 19

    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 :)

    0
  20. 20

    Five Minute Argument

    March 23, 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).

    0
  21. 21

    Good stuff! Thanks!

    0
  22. 22

    Font replacement is key. A good SEO technique.

    0
  23. 23

    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;

    0
  24. 24

    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+seo

    It’s still vague..

    0
  25. 25

    What the heck? PNG-8 alpha transparency in IE6 with no hacks? No one ever told me! Thank you Smashing Magazine!!!!

    0
  26. 26

    Sergio Ordoñez

    March 23, 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?

    0
  27. 27

    The equidistant images technique is indeed hard to achieve, I had never thought about this one, thanks!

    0
  28. 28

    @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.

    0
  29. 29

    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.

    0
  30. 30

    Nice article. I really like the alt styling idea. :)

    0
  31. 31

    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.

    0
  32. 32

    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…

    0
  33. 33

    Samantha Armacost

    March 23, 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.

    0
  34. 34

    Five Minute Argument

    March 23, 2009 7:38 am

    I love that even Chris fell foul of the ‘turn all link text into “Link”‘ filter! ;-)

    0
  35. 35

    Can Berk Güder

    March 23, 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.

    0
  36. 36

    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

    0
  37. 37

    Great article Chris, some cool things I didn’t know about here.

    0
  38. 38

    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)

    0
  39. 39

    Very useful informations, Thanks!

    0
  40. 40

    Reynald Bouttard

    March 23, 2009 10:12 am

    Thanks a lot, nice article as usual !

    0
  41. 41

    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…

    0
  42. 42

    @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.

    0
  43. 43

    I’d recommend using JQuery or Prototype for this stuff.

    Here’s a snippet for JQuery:

    $(document).ready(function(){
    $('#YourId').innerHTML = 'your_image_url';
    }

    0
  44. 44

    @ 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.

    0
  45. 45

    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?

    0
  46. 46

    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!

    0
  47. 47

    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?

    0
  48. 48

    the “alt” style thing is cool.. never gave it a thought before.. but definitely worth doing…

    0
  49. 49

    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?

    0
  50. 50

    Sergio Ordoñez

    March 24, 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.

    0
  51. 51

    Check out Cufon for font replacement: http://cufon.shoqolate.com/generate/. Requires JS, but works well and is still configurable with CSS.

    0
  52. 52

    ネキ - neki chan

    March 24, 2009 5:25 pm

    ow… i’ll try this one..
    simple but awesome :)

    0
  53. 53

    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?
    jellyFace

    CSS:
    #logo {
    width: WIDTHpx;
    height: HEIGHTpx;
    background-image: url(LOGO.png);
    background-repeat: no-repeat;
    display: block;
    text-indent: -9999px;
    }

    0
  54. 54

    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/

    0
  55. 55

    Good stuff! Thanks!

    0
  56. 56

    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.

    0
  57. 57

    3HKAeT comment6 ,

    0
  58. 58

    The equidistant objects example is a trick itself, as it will not work for the objects with varying widths – say, a menu.
    Is there a solution for equal distances between blocks of different widths?
    I found some utilizing display:inline; and text-align:justify; for the parent container, but hese are not so clear and cross-browser.

    0

↑ Back to top