[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/

↑ Back to top Tweet itShare on Facebook

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

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

    0
  2. 52

    ネキ - neki chan

    March 24, 2009 5:25 pm

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

    0
  3. 103

    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
  4. 154

    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
  5. 205

    Good stuff! Thanks!

    0
  6. 256

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

    3HKAeT comment6 ,

    0
  8. 358

    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