Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies
Showing posts with label Essentials. Show all posts
Showing posts with label Essentials. Show all posts

Saturday, November 19, 2011

CSS3 Flexible Box Layout Explained

The flexible box layout module — or “flexbox,” to use its popular nickname — is an interesting part of the W3C Working Draft. The flexbox specification is still a draft and subject to change, so keep your eyes on the W3C, but it is part of a new arsenal of properties that will revolutionize how we lay out pages. At least it will be when cross-browser support catches up.
In the meantime, we can experiment with flexbox and even use it on production websites where fallbacks will still render the page correctly. It may be a little while until we consider it as mainstream as, say, border-radius, but our job is to investigate new technologies and use them where possible. That said, when it comes to something as fundamental as page layout, we need to tread carefully.


The Display Property

So what is flexbox, and why was it created? First, let’s look at how we currently lay out pages and some of the problems with that model.
Until last year, most of us were using tables to lay out our pages. Okay, maybe not last year! But I suspect that many of you reading this have been guilty of relying on tables at some point in your career. At the same time, it actually made a lot of sense. And let’s face it: it worked… to a point. However, we all then faced the reality that tables were semantically dubious and incredibly inflexible. And through the haze of this mark-up hangover, we caught a glimpse of the future: the CSS box model. Hurray!
The CSS box model allowed us to tell the browser how to display a piece of content, and in particular how to display it as a box. We floated left and right, we tried to understand what inline-block meant, and we read countless articles about clearfix, before just copying and pasting the clearfix hack-du-jour into our CSS.
For those of us testing our websites back to IE6, we had to grapple with hasLayout and triggering it with the following or some similar fix:
* html #element {
height: 1%;
}
The box model worked, and in most cases it worked well. But as the Web entered its teenage years, it demanded more complex ways of laying out content and — thanks to a certain Mr. Ethan Marcotte — of responding to the size of the browser and/or device.

Percentage + Padding + Border = Trouble

Here’s another problem with the current box model: absolute values for padding, margin and border all affect the width of a box. Take the following:
#element {
width: 50%;
border 1px solid #000;
padding: 0 5px;
}
This will not give us a box that is 50% of its parent. It will actually render an element that is 50% of the parent’s width plus 12 pixels (2-pixel border + 10-pixel padding). You could set the padding as a percentage value (although not for input elements in Firefox!), but adding percentage values of widths to the pixel values of borders can cause mathematical problems.
There are two ways to fix this problem. The first is to use the new CSS3 box-sizing property, and setting it to border-box:
#element {
box-sizing: border-box;
width: 50%;
border 1px solid #000;
padding: 0 5px;
}
This new CSS3 panacea effectively tells the browser to render the element at the specified width, including the border width and padding.
The second way to fix this problem is to use flexbox.

Many Problems, Many Solutions

The W3C responded with a suite of answers: the flexible box model, columns, templates, positioned floats and the grid. Adobe added regions to the mix, but they are not yet supported by any browser.
The display property already has no less than a staggering 16 values: inline, block, list-item, inline-block, table, inline-table, table-row-group, table-header-group, table-footer-group, table-row, table-column-group, table-column, table-cell, table-caption, none and inherit.
And now we can add a 17th: box.

Living In A Box

Let’s take a look at flexbox, which brings with it a brand new value for the display property (box) and no less than 8 new properties. Here’s how the W3C defines the new module:
In this new box model, the children of a box are laid out either horizontally or vertically, and unused space can be assigned to a particular child or distributed among the children by assignment of flex to the children that should expand. Nesting of these boxes (horizontal inside vertical, or vertical inside horizontal) can be used to build layouts in two dimensions.
Sounds exciting! The Working Draft expands on this a little:
Flexbox… lacks many of the more complex text or document-formatting properties that can be used in block layout, such as “float” and “columns,” but in return it gains more simple and powerful tools for aligning its contents in ways that Web apps and complex Web pages often need.
Now this is beginning to sound interesting. The flexbox model picks up where the box model leaves off, and the W3C reveals its motivation by noting that “Web apps and complex Web pages” need a better layout model. Here’s a list of the new flexbox properties:
  • box-orient,
  • box-pack,
  • box-align,
  • box-flex,
  • box-flex-group,
  • box-ordinal-group,
  • box-direction,
  • box-lines.
For the sake of brevity, I will use only the official spec’s properties and values, but do remember to add the vendor prefixes to your work. (See the section on “Vendor Prefixes and Cross-Browser Support” below.)
You might also want to check out Prefixr from Jeffrey Way, which can help generate some of the CSS for you. However, I found that it incorrectly generated the display: box property, so check all of its code.

Everything Will Change

If you take the time to read or even browse the latest Working Draft (from 22 March 2011), you’ll notice a lot of red ink, and with good reason. This spec has issues and is still changing; we are in unchartered waters.
It’s worth noting that the syntax used in this article, and by all current browsers, is already out of date. The Working Draft has undergone changes to much of the syntax used in the flexbox model. For example:
display: box;
This will become:
display: flexbox;
Other changes include some properties being split (box-flex will become flex-grow and flex-shrink), while others will be combined (box-orient and box-direction will become flex-direction). Indeed, anything that starts box- will be changed to flex-. So, keep your eyes on the spec and on browser implementations. (CanIUse helps, but it doesn’t cover all of the properties.)

PaRappa the Wrapper

Using flexbox often requires an extra div or two, because the parent of any flexbox element needs to have display set to box. Before, you could get away with the following:
Content here
Content here
Now with flexbox, you’ll need:
Content here
Content here
Many of you have already turned away, insulted by this extra mark-up that is purely for presentation. That’s understandable. But here’s the thing: once you master the CSS, this extra containing div becomes a small price to pay. Indeed, you’ll often already have a containing element (not necessarily a div) to add display: box to, so there won’t be a trade-off at all.
On a broader note, sometimes you need presentational mark-up. It’s just the way it goes. I’ve found that, particularly when working on cross-browser support for a page, I have to add presentational mark-up for browsers such as IE6. I’m not saying to contract “div-itis,” but because we all use HTML5 elements in our mark-up, we find that sections often need div containers. That’s fine, as long as it’s kept to a minimum.
With this in mind, let’s get busy with some code. I’ve put together a demo page, and you can download all of the source files.
screenshot
Over the next few paragraphs, we’ll use the new flexbox model to create a basic home page for a blog. You might want to launch a latest-generation browser, though, because we’re now coding at the cutting edge. And it’s an exciting place to be.

box-flex

Let’s start with the basics: box-flex. Without box-flex, very little can be achieved. Simply put, it tells the browser how to resize an element when the element is too big or small for its parent.
Consider the following classic problem. You have a container with three children that you want to position side by side. In other words, you float them left. If the total width of these boxes is wider than that of the parent — perhaps because of padding, margin or a border — then you need to either specify exact widths in pixels (which is not flexible) or work in percentages (and the sometimes mind-bending calculations that come with them!).
Here’s the problem we have on our Fruit Blog, with three 320-pixel-wide asides (plus padding and margin) inside a 920-pixel-wide container:
screenshot
As you can see, the content is wider than the parent. However, if we set set the parent to display: box and each of these asides to box-flex: 1, then the browser takes care of the math and renders the following:
screenshot
So, what exactly has happened here?
The box-flex property refers to how the browser will treat the width of the box — or, more specifically, the unused space (even if that space is negative — i.e. even if the rendered boxes are too big for the container) — after the box has rendered. The value (1 in our example) is the ratio. So, with each aside set to a ratio of 1, each box is scaled in exactly the same way.
In the first instance, each aside was 320 pixels + 20 pixels of padding on the left and right. This gave us a total width of 360 pixels; and for three asides, the width was 1080 pixels. This is 160 pixels wider than the parent container.
Telling the browser that each box is flexible (with box-flex) will make it shrink the width of each box — i.e. it will not change the padding. This calculation is a fairly easy one:
160 pixels ÷ 3 asides = 53.333 pixels to be taken off each aside.
320 pixels – 53.333 = 266.667 pixels
And, if we look in Chrome Developer tools, we will see this is exactly how wide the box now is (rounded up to the nearest decimal):
screenshot
The same would be true if each aside had a width of 100 pixels. The browser would expand each element until it filled the unused space, which again would result in each aside having a width of 266.667 pixels.
This is invaluable for flexible layouts, Because it means that your padding, margin and border values will always be honored; the browser will simply change the width of the elements until they fit the parent. If the parent changes in size, so will the flexible boxes within it.
Of course, you can set box-flex to a different number on each element, thus creating different ratios. Let’s say you have three elements side by side, each 100 pixels wide, with 20 pixels padding, inside a 920-pixel container. It looks something like this:
screenshot
Now, let’s set the box-flex ratios:
.box1 { box-flex: 2; }
.box2 { box-flex: 1; }
.box3 { box-flex: 1; }
Here’s what it looks like:
screenshot
What just happened?!
Well, each aside started off as 140-pixels wide (100 pixels + 40 pixels padding), or 420 pixels in total. This means that 500 pixels were left to fill once we’d made them flexible boxes.
However, rather than split the 500 pixels three ways, we told the browser to assign the first aside with a box-flex of 2. This would grow it by 2 pixels for every 1 pixel that the other two boxes grow, until the parent is full.
Perhaps the best way to think of this is that our ratio is 2:1:1. So, the first element will take up 2/4 of the unused space, while the other two elements will take up 1/4 of the unused space (2/4 + 1/4 + 1/4 = 1).
2/4 of 500 pixels is 250, and 1/4 is 125 pixels. The final widths, therefore, end up as:
.box1 = 350px (100px + 250px) + 40px padding
.box2 = 225px (100px + 125px) + 40px padding
.box3 = 225px (100px + 125px) + 40px padding
Add all of these values up and you reach the magic number of 920 pixels, the width of our parent.
An important distinction to make is that the ratio refers to how the additional pixels (or unused space) are calculated, not the widths of the boxes themselves. This is why the widths are 350:225:225 pixels, and not 460:230:230 pixels.
The wonderful thing about the flexbox model is that you don’t have to remember — or even particularly understand — much of the math. While the Working Draft goes into detail on the calculation and distribution of free space, you can work safe in the knowledge that the browser will take care of this for you.

Animating Flexible Boxes

A simple and elegant effect is already at your fingertips. By making the li elements in a navigation bar flexible, and specifying their width on :hover, you can create a nice effect whereby the highlighted li element expands and all the other elements shrink. Here’s the CSS for that:
nav ul {
display: box;
width: 880px;
}

nav ul li {
padding: 2px 5px;
box-flex: 1;
-webkit-transition: width 0.5s ease-out;
min-width: 100px;
}

nav ul li:hover {
width: 200px;
}
screenshot
You’ll spot a min-width on the li element, which is used to fix a display bug in Chrome.

Equal-Height Columns: The Happy Accident!

As we’ll see, all flexbox elements inherit a default value of box-align: stretch. This means they will all stretch to fill their container.
For example, two flexbox columns in a parent with display: box will always be the same height. This has been the subject of CSS and JavaScript hacks for years now.
There are a number of practical implementations of this fortunate outcome, not the least of which is that sidebars can be made the same height as the main content. Now, a border-left on a right-hand sidebar will stretch the full length of the content. Happy days!

box-orient and box-direction

The box-orient property defines how boxes align within their parent. The default state is horizontal or, more specifically, inline-axis, which is horizontal and left-to-right in most Western cultures. Likewise, vertical is the same as block-axis. This will make sense if you think about how the browser lays out inline and block elements.
You can change the box-orient value to vertical to make boxes stack on top of each other. This is what we’ll do with the featured articles on our fruit blog.
Here is what our articles look like with box-orient set to its default setting:
screenshot
Ouch! As you can see, the articles are stacking next to each other and so run off the side of the page. It also means that they sit on top of the sidebar. But by quickly setting the parent div to box-orient: vertical, the result is instant:
screenshot
A related property is box-direction, which specifies the direction in which the boxes are displayed. The default value is normal, which means the boxes will display as they appear in the code. But if you change this value to reverse, it will reverse the order, and so the last element in the code will appear first, and the first last.
While box-orient and box-direction are essential parts of the model, they will not likely appear in the final specification, because they are being merged into the flex-direction property, which will take the following values: lr, rl, tb, bt, inline, inline-reverse, block and block-reverse. Most of these are self-explanatory, but as yet they don’t work in any browser.

box-ordinal-group

Control over the order in which boxes are displayed does not stop at normal and reverse. You can specify the exact order in which each box is placed.
The value of box-ordinal-group is set as a positive integer. The lower the number (1 being the lowest), the higher the layout priority. So, an element with box-ordinal-group: 1 will be rendered before one with box-ordinal-group: 2. If elements share the same box-ordinal-group, then they will be rendered in the order that they appear in the HTML.
Let’s apply this to a classic blog scenario: the sticky post (i.e. content that you want to keep at the top of the page). Now we can tag sticky posts with a box-ordinal-group value of 1 and all other posts with a box-ordinal-group of 2 or lower. It might look something like this:
article {
box-ordinal-group: 2;
}

article.sticky {
box-ordinal-group: 1;
}
So, any article with class="sticky" is moved to the top of the list, without the need for any front-end or back-end jiggering. That’s pretty impressive and incredibly useful.
We’ve used this code in our example to stick a recent blog post to the top of the home page:
screenshot

box-pack and box-align

The box-pack and box-align properties help us position boxes on the page.
The default value for box-align is stretch, and this is what we’ve been using implicitly so far. The stretch value stretches the box to fit the container (together with any other siblings that are flexible boxes), and this is the behavior we’ve seen so far. But we can also set box-align to center and, depending on the box-orient value, the element will be centered either vertically or horizontally.
For example, if a parent inherits the default box-align value of horizontal (inline-axis), then any element with box-align set to center will be centered vertically.
We can use this in our blog example to vertically center the search box in the header. Here’s the mark-up:
And to vertically center the search box, we need just one line of CSS:
header {
display: box; box-align: center;
}

header #search {
display: box; box-flex: 1;
}
The height of #search has not been set and so depends on the element’s content. But no matter what the height of #search, it will always be vertically centered within the header. No more CSS hacks for you!
screenshot
The other three properties of box-align are start, end and baseline.
When box-orient is set to horizontal (inline-axis), an element with box-align set to start will appear on the left, and one with box-align set to end will appear on the right. Likewise, when box-orient is set to vertical (block-axis), an element with box-align set to start will appear at the top, and one with box-align set to end will move to the bottom. However, box-direction: reverse will flip all of these rules on their head, so be warned!
Finally, we have baseline, which is best explained by the specification:
Align all flexbox items so that their baselines line up, then distribute free space above and below the content. This only has an effect on flexbox items with a horizontal baseline in a horizontal flexbox, or flexbox items with a vertical baseline in a vertical flexbox. Otherwise, alignment for that flexbox item proceeds as if flex-align: auto had been specified.
Another property helps us with alignment: box-pack. This enables us to align elements on the axis that is perpendicular to the axis they are laid out on. So, as in the search-bar example, we have vertically aligned objects whose parent have box-orient set to horizontal.
But what if we want to horizontally center a box that is already horizontally positioned? For this tricky task, we need box-pack.
If you look at the navigation on our fruit blog, you’ll see that it’s only 880 pixels wide, and so it naturally starts at the left of the container.
screenshot
We can reposition this ul by applying box-pack to its parent. If we apply box-pack: center to the navigation element, then the navigation moves nicely to the center of the container.
screenshot
This behaves much like margin: 0 auto. But with the margin trick, you must specify an explicit width for the element. Also, we can do more than just center the navigation with box-pack. There are three other values: start, end and justify. The start and end values do what they do for box-align. But justify is slightly different.
The justify value acts the same as start if there is only one element. But if there is more than one element, then it does the following:
  • It adds no additional space in front of the first element,
  • It adds no additional space after the last element,
  • It divides the remaining space between each element evenly.

box-flex-group and box-lines

The final two properties have limited and/or no support in browsers, but they are worth mentioning for the sake of thoroughness.
Perhaps the least helpful is box-flex-group, which allows you to specify the priority in which boxes are resized. The lower the value (as a positive integer), the higher the priority. But I have yet to see an implementation of this that is either useful or functional. If you know different, please say so in the comments.
On the other hand, box-lines is a bit more practical, if still a little experimental. By default, box-lines is set to single, which means that all of your boxes will be forced onto one row of the layout (or onto one column, depending on the box-orient value). But if you change it to box-lines: multiple whenever a box is wider or taller than its parent, then any subsequent boxes will be moved to a new row or column.

Vendor Prefixes and Cross-Browser Support

It will come as no surprise to you that Internet Explorer does not (yet) support the flexbox model. Here’s how CanIUse sees the current browser landscape for flexbox:
screenshot
The good news is that Internet Explorer 10 is coming to the party. Download the platform preview.
Also, we need to add a bunch of vendor prefixes to guarantee the widest possible support among other “modern” browsers. In a perfect world, we could rely on the following:
#parent {
display: box;
}

#child {
flex-box: 1;
}
But in the real world, we need to be more explicit:
#parent {
display: -webkit-box;
display: -moz-box;
display: -o-box;
display: box;
}

#child {
-webkit-flex-box: 1;
-moz-flex-box: 1;
-o-flex-box: 1;
flex-box: 1;
}

Helper Classes

A shortcut to all of these vendor prefixes — and any page that relies on the flexbox model will have many of them — is to use helper classes. I’ve included them in the source code that accompanies this article. Here’s an example:
.box {
display: -webkit-box;
display: -moz-box;
display: -o-box;
display: box;
}

.flex1 {
-webkit-flex-box: 1;
-moz-flex-box: 1;
-o-flex-box: 1;
flex-box: 1;
}

.flex2 {
-webkit-flex-box: 2;
-moz-flex-box: 2;
-o-flex-box: 2;
flex-box: 2;
}
This allows us to use this simple HTML:
helper classes is considered bad practice by many; but with so many vendor prefixes, the shortcut can probably be forgiven. You might also consider using a “mixin” with Sass or Less, which will do the same job. This is something that Twitter sanctions in its preboot.less file.

Flexie.js

For those of you who want to start experimenting with flexbox now but are worried about IE support, a JavaScript polyfill is available to help you out. Flexie.js, by Richard Herrera, is a plug-and-play file that you simply need to include in your HTML (download it on GitHub). It will then search through your CSS files and make the necessary adjustments for IE — no small feat given that it is remapping much of the layout mark-up on the page. screenshot

A Word on Firefox

The flexbox model was, at least originally, based on a syntax that Mozilla used in its products. That syntax, called XUL, is a mark-up language designed for user interfaces. The irony here is that Firefox is still catching up, and its rendering of some flexbox properties can be buggy. Below are some issues to watch out for, which future releases of Firefox will fix. Credit here must go to the uber-smart Peter Gasston and Oli Studholme, giants on whose shoulders I stand.
  • Flexbox ignores overflow: hidden and expands the flexbox child when the content is larger than the child’s width.
  • The setting display: box is treated as display: inline-box if there is no width.
  • The outline on flexbox children is padded as if by a transparent border of the same width.
  • The setting box-align: justify does not work in Firefox.
  • If you set box-flex to 0, Firefox forces the element to act like it’s using the quirks-mode box model.

Summary

The flexbox model is another exciting development in the CSS3 specification, but the technology is still very much cutting-edge. With buggy support in Firefox and no support in Internet Explorer until version 10 moves beyond the platform preview, it is perhaps of limited use in the mainstream. Nevertheless, the spec is still a working document. So, by experimenting with these new techniques now, you can actively contribute to its development. It’s hard to recommend the flexbox model for production websites, but envelopes need pushing, and it might well be the perfect way to lay out a new experimental website or idea that you’ve been working on. Offering a range of new features that help us break free of the float, the flexbox model is another step forward for the layout of modern Web pages and applications. It will be interesting to see how the specification develops and what other delights for laying out pages await the Web design community in the near future.

Further Reading

From floats to flexbox, here’s everything else you need to know:

Saturday, November 12, 2011

The Definitive Guide to Using Negative Margins

Since the recommendation of CSS2 back in 1998, the use of tables has slowly faded into the background and into the history books. Because of this, CSS layouts have since then been synonymous with coding elegance.
Out of all the CSS concepts designers have ever used, an award probably needs to be given to the use of Negative Margins as being the most least talked about method of positioning. It’s like an online taboo—everyone’s doing it, yet no one wants to talk about it.

1. Setting the record straight

We all use margins in our CSS, but when it comes to negative margins, our relationship somehow manages to take a turn for the worse. The use of negative margins in web design is so divided that while some of us absolutely love it, there are also those who simply think it’s the work of the devil.
A negative margin looks like this:
1#content {margin-left:-100px;}
Negative margins are usually applied in small doses but as you’ll see later on, it’s capable of so much more. A few things to note about negative margins are:
  • They are extremely valid CSS
    I’m not kidding on this one. W3C even says that, “Negative values for margin properties are allowed…” ‘Nuff said. Check out the article for more details.
  • Negative margins are not a hack
    This is especially true. It’s because of not understanding negative margins properly that it got its hackish image. It only becomes a hack if you use it to fix an error you made elsewhere.
  • It goes with the flow
    It does not break the flow of the page if applied to elements without floats. So if you use a negative margin to nudge an element upwards, all succeeding elements will be nudged as well.
  • It is highly compatible
    Negative margins are wholly supported across all modern browsers (and IE6 in most cases).
  • It reacts differently when floats are applied
    Negative margins are not your everyday CSS so they should be applied with care.
  • Dreamweaver doesn’t understand it
    Negative margins don’t show up in the Design View of DW. Why are you even checking your site in Design View anyway?

2. Working with negative margins

Negative margins are very powerful when used correctly. There are 2 types of scenarios where negative margins take center stage.

Negative Margins on Static Elements

Negative margins motion on static elements
A static element is an element with no float applied. The image below illustrates how static elements react to negative margins.
  • When a static element is given a negative margin on the top/left, it pulls the element in that specified direction. For example:
    1/* Moves the element 10px upwards */
    2 
    3#mydiv1 {margin-top:-10px;}
  • But if you apply it to the bottom/right, it doesn’t move the element down/right as you might think. Instead, it pulls any succeeding element into the main element, overlapping it.
    1/*
    2* All elements succeeding #mydiv1 move up by
    3* 10px, while #mydiv1 doesn’t even move an inch.
    4*/
    5 
    6#mydiv1 {margin-bottom:-10px;}
  • If no width is applied, adding Negative Margins to its left/right pulls the element in both directions increasing its width. It’s here that the margin acts like a padding.

Negative Margins on Floated Elements

Consider this as our actual markup:
HTML
First
Second
  • If a negative margin is applied opposite a float, it creates a void leading to the overlapping of content. This is great for liquid layouts where one column has a width of 100% while the other has a definite width, like 100px.
    1/* A negative margin is applied opposite the float */
    2#mydiv1 {float:left; margin-right:-100px;}
  • If both elements are floated left and margin-right:-20px is applied to #mydiv1, #mydiv2 treats #mydiv1 as if it were 20px smaller in width than it actually is (thus, overlapping it). What’s interesting is that the contents of #mydiv1 don’t react at all and continue to retain its current width.
  • If the negative margin is equal to the actual width, then it overlaps it entirely. This is because margins, padding, borders, and width add up to the total width of an element. So if a negative margin is equal to the rest of the dimensions then the element’s width effectively becomes 0px.

3. Effective Techniques

Since we now know that applying a negative margin is valid CSS2 code, using it provides for some very interesting CSS techniques:

Making a single
    into a 3-column list

Splitting a list into 3 columns
If you have a list of items which are just too long to display vertically, why not divide them into columns instead? Negative margins let you do this without having to add any floats or additional tags. It’s amazing how it easily lets you divide the list below into 3 separate columns, like so:
HTML
  • Eggs
  • Ham
  • Bread
  • Butter
  • Flour
  • Cream
CSS
1ul {list-style:none;}
2li {line-height:1.3em;}
3.col2 {margin-left:100px;}
4.col3 {margin-left:200px;}
5.top {margin-top:-2.6em;} /* the clincher */
By adding margin-top:-2.6em (twice the line-height of
  • ) to .top, all elements move up in perfect alignment. Using a negative margin is more appropriate than applying relative positioning since you only have to apply it to the first of the new columns instead of to each


  • tag. Cool, huh?

    Overlap for added emphasis

    Phlashers.com
    Overlapping elements on purpose is also a good design metaphor. It adds emphasis to specific elements since the overlapping effect creates the illusion of depth. A good example would be the comments section of Phlashers.com, which uses an overlapping technique to draw attention to the number of comments a post has. Combine this with the z-index property and a little creativity and you’ve got it made.

    Smashing 3D text effects

    3D effects
    Here’s a neat trick. Create Safari-like text, which are slightly beveled by creating 2 versions of your text in 2 different colors. Then use negative margins to overlap one over the other with a discrepancy of around 1 or 2 pixels and you’ve got selectable, robot-friendly beveled text! No need for huge jpegs or gifs which devour bandwidth like fat pigs.

    Simple 2-column Layouts

    Negative margins are also a great way to create simple 2-column liquid layouts where the sidebar has a preset width and the content has a liquid width of 100%
    HTML
    Main content in here
    CSS
    1#content {width:100%; float:left; margin-right:-200px;}
    2#sidebar {width:200px; float:left;}
    And there you have a simple 2-column layout record time. It works flawlessly in IE6 too! Now, to prevent #sidebar from overlapping the text inside #content, simply add
    1/* Prevent text from being overlapped */
    2 
    3#content p {margin-right:210px;}
    4 
    5/* It’s 200px + 10px, the 10px being an additional margin.*/
    When used properly, negative margins can also provide what’s called a Flexible Document Structure which absolutely kicks tables in the face. Flexible Document Structure is an accessibility and SEO technique which allows you to arrange your markup in almost any order depending on your intentions. Tom Wright wrote an interesting article which discusses possible applications of negative margins in multicolumn layouts.

    Nudging elements into place

    This is the most common (and simplest) usage for negative margins. If you’re inserting a 10th div in a sea of 9 other divs and somehow it just won’t align properly, use negative margins to nudge that 10th div into place instead of having to edit the other 9.

    4. Bugfixes

    Text and Link problems

    Using negative margins with floats sometimes pisses off older browsers. Some symptoms include:
    • Making links unclickable
    • Text becomes difficult to select
    • Tabbing any links disappears when you lose focus
    Solution: Just add position:relative and it works!

    My picture got cut-off

    If you have the bad luck of using IE6 in the office, sometimes content will suddenly be cut-off when overlapping and floats are concerned.
    Solution: Again, just add position:relative to the floated element and everything goes back to normal.

    5. Conclusion

    Negative margins have a place in modern web design because of its ability to position elements without any additional markup. With more users switching to more updated browsers (IE8 included), the future looks very bright for sites which rely on this technique.
    If you have any unique experiences with negative margins, let me know by posting a comment.

    6. Resources

    More info on negative margins.


  • The Z-Index CSS Property: A Comprehensive Look

    Most CSS properties are quite simple to deal with. Often, applying a CSS property to an element in your markup will have instant results — as soon as you refresh the page, the value set for the property takes effect, and you see the result immediately. Other CSS properties, however, are a little more complex and will only work under a given set of circumstances.
    The z-index property belongs to the latter group. z-index has undoubtedly caused as much confusion and frustration as any other CSS property. Ironically, however, when z-index is fully understood, it is a very easy property to use, and offers an effective method for overcoming many layout challenges.
    In this article, we’ll explain exactly what z-index is, how it has been misunderstood, and we’ll discuss some practical uses for it. We’ll also describe some of the browser differences that can occur, particularly in previous versions of Internet Explorer and Firefox. This comprehensive look at z-index should provide developers with an excellent foundation to be able to use this property confidently and effectively.

    What is it?

    The z-index property determines the stack level of an HTML element. The “stack level” refers to the element’s position on the Z axis (as opposed to the X axis or Y axis). A higher z-index value means the element will be closer to the top of the stacking order. This stacking order runs perpendicular to the display, or viewport.

    3-dimensional representation of the Z axis:

    3-D Representation of the Z Axis
    In order to clearly demonstrate how z-index works, the image above exaggerates the display of stacked elements in relation to the viewport.

    The Natural Stacking Order

    In an HTML page, the natural stacking order (i.e. the order of elements on the Z axis) is determined by a number of factors. Below is a list showing the order that items fit into a stacking context, starting with the bottom of the stack. This list assumes none of the items has z-index applied:
    • Background and borders of the element that establish stacking context
    • Elements with negative stacking contexts, in order of appearance
    • Non-positioned, non-floated, block-level elements, in order of appearance
    • Non-positioned, floated elements, in order of appearance
    • Inline elements, in order of appearance
    • Positioned elements, in order of appearance
    The z-index property, when applied correctly, can change this natural stacking order.
    Of course, the stacking order of elements is not evident unless elements are positioned to overlap one another. Thus, to see the natural stacking order, negative margins can be used as shown below:
    Grey Box
    Blue Box
    Gold Box
    The boxes above are given different background and border colors, and the last two are indented and given negative top margins so you can see the natural stacking order. The grey box appears first in the markup, the blue box second, and the gold box third. The applied negative margins clearly demonstrate this fact. These elements do not have z-index values set; their stacking order is the natural, or default, order. The overlaps that occur are due to the negative margins.

    Why Does it Cause Confusion?

    Although z-index is not a difficult property to understand, due to false assumptions it can cause confusion for beginning developers. This confusion occurs because z-index will only work on an element whose position property has been explicitly set to absolute, fixed, or relative.
    To demonstrate that z-index only works on positioned elements, here are the same three boxes with z-index values applied to attempt to reverse their stacking order:
    Grey Box
    Blue Box
    Gold Box
    The grey box has a z-index value of “9999″; the blue box has a z-index value of “500″; and the gold box has a z-index value of “1″. Logically, you would assume that the stacking order of these boxes should now be reversed. But that is not the case, because none of these elements has the position property set.
    Here are the same boxes with position: relative added to each, and their z-index values maintained:
    Grey Box
    Blue Box
    Gold Box
    Now the result is as expected: The stacking order of the elements is reversed; the grey box overlaps the blue box, and the blue box overlaps the gold.

    Syntax

    The z-index property can affect the stack order of both block-level and inline elements, and is declared by a positive or negative integer value, or a value of auto. A value of auto gives the element the same stack order as its parent.
    Here is the CSS code for the third example above, where the z-index property is applied correctly:
    #grey_box {
     width: 200px;
     height: 200px;
     border: solid 1px #ccc;
     background: #ddd;
     position: relative;
     z-index: 9999;
    }
    
    #blue_box {
     width: 200px;
     height: 200px;
     border: solid 1px #4a7497;
     background: #8daac3;
     position: relative;
     z-index: 500;
    }
    
    #gold_box {
     width: 200px;
     height: 200px;
     border: solid 1px #8b6125;
     background: #ba945d;
     position: relative;
     z-index: 1;
    }
    
    Again, it cannot be stressed enough, especially for beginning CSS developers, that the z-index property will not work unless it is applied to a positioned element.

    JavaScript Usage

    If you want to affect the z-index value of an element dynamically via JavaScript, the syntax is similar to how most other CSS properties are accessed, using “camel casing” to replace hyphenated CSS properties, as in the code shown below:
    var myElement = document.getElementById("gold_box");
    myElement.style.position = "relative";
    myElement.style.zIndex = "9999";
    
    In the above code, the CSS syntax “z-index” becomes “zIndex”. Similarly, “background-color” becomes “backgroundColor”, “font-weight” becomes “fontWeight”, and so on.
    Also, the position property is changed using the above code to again emphasize that z-index only works on elements that are positioned.

    Improper Implementations in IE and Firefox

    Under certain circumstances, there are some small inconsistencies in Internet Explorer versions 6 and 7 and Firefox version 2 with regards to the implementation of the z-index property.

    element is a windowed control, and so will always appear at the top of the stacking order regardless of natural stack order, position values, or z-index. This problem is illustrated in the screen capture below:

    The element.
    This bug in IE6 has caused problems with drop-down menus that fail to overlap element, then make it reappear when the overlapping menu disappears. Another solution involves using an

    Guide to CSS Font Stacks: Techniques and Resources

    CSS Font stacks are one of those things that elude a lot of designers. Many stick to the basic stacks Dreamweaver auto-recommends or go even more basic by just specifying a single web-safe font.
    But doing either of those things means you’re missing out on some great typography options. Font stacks can make it possible to show at least some of your visitors your site’s typography exactly the way you intend without showing everyone else a default font. Read on for more information on using and creating effective font stacks with CSS.

    Creating Your Own Font Stacks

    There are a huge variety of font stacks recommended. It seems every designer has their own favorites, what they consider to be the “ultimate” font stack. While there is no definitive font stack out there, there are a few things to keep in mind when using or creating your own stacks.
    First of all, make sure you always include a generic font family at the end of your font stacks. This way, if for some strange reason the person visiting your site has virtually no fonts installed, at least they won’t end up looking at everything in Courier New. Second, there’s a basic formula to creating a good font stack: ‘Preferred Font’, ‘Next best thing’, ‘Something common and sorta close’, ‘Similar Web-safe’, ‘Generic font’. There’s nothing wrong with having more than one font for any of those, but try to keep your font stack reasonably short (six to ten fonts is a pretty good maximum number).
    Third, make sure you pay attention to the scale of the fonts in your stack. One common thing I see in font stacks is the inclusion of Verdana and Arial or Helvetica in the same stack. Verdana is a very wide font; Arial is relatively narrow. In effect, this can make your site’s typography appear very differently to different visitors. The same goes for Times New Roman (narrow) and Georgia (wide). Considering both Arial/Helvetica and Verdana are considered web-safe (same goes for Times/Times New Roman and Georgia), it doesn’t make much sense to include both.

    Common Font Stacks

    A lot of designers out there have taken a crack at creating ideal font stacks. While I have yet to see an “ultimate” font stack, there are plenty of really great ones out there to choose from if you don’t want to take the time create your own custom stacks. Here are some of the good ones we’ve seen.

    Better CSS Font Stacks

    Unit Interactive published an article last summer with a collection of “better” CSS font stacks. The list is extensive, with font stacks that should satisfy just about anyone. Fonts are listed out according to whether they’re appropriate for headlines or body content.
    Here are some listed for body text:
    • Baskerville, ‘Times New Roman’, Times, serif
    • Garamond, ‘Hoefler Text’, ‘Times New Roman’, Times, serif
    • Geneva, ‘Lucida Sans’, ‘Lucida Grande’, ‘Lucida Sans Unicode’, Verdana, sans-serif
    • GillSans, Calibri, Trebuchet, sans-serif
    Screenshot
    For headlines:
    • Georgia, Times, ‘Times New Roman’, serif
    • Palatino, ‘Palatino Linotype’, ‘Hoefler Text’, Times, ‘Times New Roman’, serif
    • Tahoma, Verdana, Geneva
    • Trebuchet, Tahoma, Arial, sans-serif
    Screenshot
    And a few that are balanced for either body or headline text:
    • Impact, Haettenschweiler, ‘Arial Narrow Bold’, sans-serif
    • Cambria, Georgia, Times, ‘Times New Roman’, serif
    • ‘Copperplate Light’, ‘Copperplate Gothic Light’, serif
    • Futura, ‘Century Gothic’, AppleGothic, sans-serif
    Screenshot

    8 Definitive Web Font Stacks

    This article from Sitepoint written by Michael Tuck lists eight font stacks that are supposed to be the ultimate stacks for any application. It’s based on a basic formula of: ‘exact font’, ‘nearest alternative’, ‘platform-wide alternative(s)’, ‘universal (cross-platform) choice(s)’, generic. My biggest issues with some of these font stacks is their length; is it really necessary to include 17 different fonts in a single font stack? I don’t think so…
    Screenshot
    The font stacks:
    • The Times New Roman-based serif stack: Cambria, ‘Hoefler Text’, Utopia, ‘Liberation Serif’, ‘Nimbus Roman No9 L Regular’, Times, ‘Times New Roman’, serif
    • A Modern Georgia-based serif stack: Constantia, ‘Lucida Bright’, Lucidabright, ‘Lucida Serif’, Lucida, ‘DejaVu Serif’, ‘Bitstream Vera Serif’, ‘Liberation Serif’, Georgia, serif
    • A more traditional Garamond-based serif stack: ‘Palatino Linotype’, Palatino, Palladio, ‘URW Palladio L’, ‘Book Antiqua’, Baskerville, ‘Bookman Old Style’, ‘Bitstream Charter’, ‘Nimbus Roman No9 L’, Garamond, ‘Apple Garamond’, ‘ITC Garamond Narrow’, ‘New Century Schoolbook’, ‘Century Schoolbook’, ‘Century Schoolbook L’, Georgia, serif
    • The Helvetica/Arial-based sans serif stack: Frutiger, ‘Frutiger Linotype’, Univers, Calibri, ‘Gill Sans’, ‘Gill Sans MT’, ‘Myriad Pro’, Myriad, ‘DejaVu Sans Condensed’, ‘Liberation Sans’, ‘Nimbus Sans L’, Tahoma, Geneva, ‘Helvetica Neue’, Helvetica, Arial, sans-serif
    • The Verdana-based sans serif stack: Corbel, ‘Lucida Grande’, ‘Lucida Sans Unicode’, ‘DejaVu Sans’, ‘Bitstream Vera Sans’, ‘Liberation Sans’, Verdana, ‘Verdana Ref’, sans-serif
    • The Trebuchet-based sans serif stack: ‘Segoe UI’, Candara, ‘Bitstream Vera Sans’, ‘DejaVu Sans’, ‘Bitsream Vera Sans’, ‘Trebuchet MS’, Verdana, ‘Verdana Ref’, sans-serif
    • The heavier “Impact” sans serif stack: Impact, Haettenschweiler, ‘Franklin Gothic Bold’, Charcoal, ‘Helvetica Inserat’, ‘Bitstream Vera Sans Bold’, ‘Arial Black’, sans-serif
    • The Monospace stack: Consolas, ‘Andale Mono WT’, ‘Andale Mono’, ‘Lucida Console’, ‘Lucida Sans Typewriter’, ‘DejaVu Sans Mono’, ‘Bitstream Vera Sans Mono’, ‘Liberation Mono’, ‘Nimbus Mono L’, Monaco, ‘Courier New’, Courier, monospace

    The Myth of ‘Web-Safe’ Fonts

    The Myth of ‘Web-Safe’ Fonts from Safalra.com offers up five simple, straightforward font stacks for web typography. These stacks are pretty bare-bones as far as most recommended font stacks go, but they’re perfectly adequate for many applications, as well as being a good starting point for building your own stacks.
    • The ‘wide’ sans serif stack: Verdana, Geneva, sans-serif
    • The ‘narrow’ sans serif stack: Tahoma, Arial, Helvetica, sans-serif
    • The ‘wide” serif stack: Georgia, Utopia, Palatino, ‘Palatino Linotype’, serif
    • The ‘narrow’ serif stack: ‘Times New Roman’, Times, serif
    • The monospace stack: ‘Courier New’, Courier, monospace
    Screenshot

    Tools

    Font Matrix

    Font Matrix is a font comparison tool that lists fonts bundled with Windows XP, Windows Vista, Mac OS X Tiger, Mac OS X Leopard, Microsoft Office (2003, 2007 and 2004 for Mac) and the Adobe Creative Suite. The chart shows which software bundles and operating systems come with which fonts, so you can get a good idea of how common a particular font might be. This is an incredibly valuable tool for those looking to create their own custom font stacks.
    Screenshot

    Complete Guide to Pre-Installed Fonts in Linux, Mac and Windows

    Here’s another chart that shows the fonts commonly installed on Linux, Mac and Windows machines, grouped together by family and similarity. It’s another really valuable tool for font stack creators.
    Screenshot

    Typechart

    Typechart shows you web-safe and common fonts and suggests different sizes and styles for headings, paragraphs, and other typographic elements. There are a ton of different browsing options, and you can preview the way fonts will look on both Windows and Mac machines before downloading the CSS. The only drawback to Typechart is that it only includes a handful of fonts: Arial/Helvetica, Cambria, Georgia, Lucida Grande, Lucida Sans Unicode, Trebuchet MS, and Verdana.
    Screenshot

    Typetester

    Typetester lets you try out up to three fonts side-by-side. This can be a great way to test font stacks to see what the differences will be as the stacks degrade. You can use any font on your system, though it does categorize fonts by web safe, Windows default, and Mac default, making it easier to create stacks without other reference materials.
    Screenshot

    Font Stack Builder

    Code Style offers the Font Stack Builder for creating font stacks based on font family, and whether the fonts are generally installed on Windows, Mac or Linux machines. You can add as many fonts as you want and it will show you a grid with how common those fonts are on different kinds of machines.
    Screenshot

    Articles

    There are hundreds of articles out there about font stacks. Some have been mentioned above, but there are plenty of others that deserve some recognition. Here are a few:
    Striking Web Sites with Font Stacks that Inspire
    This article covers twenty different websites with excellent font stacks. Basic web-safe and common fonts are covered along with more creative font stacks. It’s a great resource for getting some inspiration before creating your own stacks.
    Screenshot
    Better Font Families in CSS
    This article from Devlounge gives a very brief overview of the author’s favored font stacks, as well as a few tips for creating your own stacks.
    Screenshot
    The New Typography
    This article gives a great overview of creating font stacks and good web typography. There are plenty of tips mentioned, including which fonts to avoid using in the same font stacks and why.
    Screenshot
    Roundup: CSS Font Stacks
    This article is a great introduction to CSS font stacks and how to use them effectively. It includes some tools, tips, and other information about creating your own font stacks or choosing which ones to use.
    Screenshot

    Excellent Font Stack Examples

    Here’s a handful of sites that have excellent font stacks and great typography in general. You can find more examples at Typesites.
    Screenshot
    Font stack: “Helvetica Neue”, Helvetica, Arial, sans-serif
    Screenshot
    Font stack: “Lucida Fax”, Georgia, Helvetica, Arial, sans-serif
    Screenshot
    Font stack: Baskerville, Palatino, ‘Palatino Linotype’, Georgia, Serif
    Screenshot
    Font stack: “Lucida Grande”, Geneva, Helvetica, sans-serif (used for some of the headings and meta information)
    Screenshot
    Font stack: “Adobe Caslon Pro”, “Hoefler Text”, Georgia, Garamond, Times, serif (pretty nice stack for what is primarily a holding page!)
    Screenshot
    Font stack: “Courier new”, Courier, “Andale Mono”
    Screenshot
    Font stack: Gotham, “Helvetica Neue”, Helvetica, Arial, sans-serif;
    Screenshot
    Font stack: Arial, sans-serif
    Screenshot
    Font stack: “Lucida Grande”, Tahoma, Verdana, sans-serif
    Screenshot
    Font stack: Helvetica, Arial, sans-serif
    Screenshot
    Font stack:“Arial black”, arial, sans-serif
    Screenshot
    Font stack:Arial, Helvetica, sans-serif
    Screenshot
    Font stack: Arial, “Helvetica Neue”, Helvetica, sans-serif
    Screenshot
    Font stack:“Myriad Pro”, Helvetica, Arial, sans-serif
    Screenshot
    Font stack: “Lucida Grande”, Arial, Verdana, Helvetica, sans-serif
    Screenshot
    Font stack: Georgia, “Times New Roman”, Times, serif