Sei sulla pagina 1di 6

Do You Want To Do That With CSS?

Align Elements Left and Right


By: John Gallant , Holly Bergevin ,
This series will deal with various CSS "tasks," those things designers wish to have happen in the display of their pages, using CSS, which seem like they ought to be simple to do. Sometimes the design will require items to occupy certain positions, or text might need to wrap around images in a certain way. There are many possibilities. Previously, one might have easily accomplished the task using a table (or two), or perhaps other coding practices that are now recognized as less than ideal because they might bloat pages, or are not as efficient as they could be. The need for accomplishing the tasks is common to most web authors sooner or later, but the techniques used to do them are not widely known in the community yet, causing thousands to "reinvent the wheel" daily. It's got to stop sometime, so why not now?

Hitting Both Sides


Our first "task" involves placing two items in a box, and having them display on opposite sides of said box. They might be a pair of images, one left and one right, or a business name and a phone number, or perhaps a header that needs a logo at one end and navigation text at the other. It could be any number of things. This sounds simple, and it is. Skilled table coders can do this automatically, but surprisingly, many people have difficulty doing it without benefit of tables. Well, we're going to show you that CSS rules do make it possible, using either of two methods. So, counting tables, that's three methods to accomplish the task, and we all know that three is better than one, right? To some it might seem that having oppositely placed elements is not a big issue, but requests for help on this task come up quite often on CSS forums. Apparently, the need for oppositely aligned elements is rather common. That being understood, let's "spread out."

The "Absolute" Method


Using absolute positioning (or AP for short), it is possible to place page elements anywhere within a box, subject to certain constraints inherent in the method. Thus, you may have an element on one side of a box and another element over against the opposite side. All it takes is the correct CSS, and those items are pasted in the desired spots.

1 of 6

Notice we said pasted, because that's exactly what happens. Such AP elements are indeed placed on the sides, but they are also removed from the flow of the parent box, meaning their placement is not taken into consideration by non-AP elements within the box. Depending on source order or z-index, non-AP elements may get covered up by these AP elements. If no other content is within the box besides the AP elements, then no cover-up can happen, but then the box has no "real" flowed content that can stretch it vertically. The AP elements won't do this because they are no longer in the flow (taking up space), and unlike floated elements, AP elements cannot be cleared. So in this case, it is necessary to set some height value to the container box or it will have no screen height, and the AP elements will hang down from the container like flags from a balcony.
The Details

When using this method, several things must be done.


Unless the AP elements are to appear at the viewport edges, you'll need to make sure that their containing box is itself positioned, either relatively or absolutely. For more details on what this means, see Web Terminology: Part Three (http://www.communitymx.com/abstract.cfm?cid=75A8C) . Each AP element will need a stated width that won't cause them to overlap one another, unless you want that to happen, that is. Unlike floats, AP elements can't interfere with any other elements, so overlapping is the main issue to deal with once they are properly located. If you leave off widths for the AP elements, some browsers "shrink-wrap" the content within the AP box and others make the AP box full width. It's best for now to use some kind of width. As mentioned, any normally flowed content within the box may get covered by these AP boxes, so some provision is usually made to prevent this from happening. A simple side padding in the container box may be all that's needed, or a more specific arrangement may need to be worked out. All that really matters is that the flowed content be kept out of the areas that will be covered by the AP elements. Finally, depending on the widths you've given the AP elements, you may need to make sure that the inline content of the right side AP element is aligned to the right.

So let's look at the code needed to have our two elements aligned on opposite sides of a box.

The HTML: <div class="container"> <div class="left-element"> Content in left item </div> <div class="right-element"> Content in right item </div> </div>

2 of 6

The CSS: .container { position: relative; height: 50px; } .left-element { position: absolute; left: 0; width: 50%; } .right-element { position: absolute; right: 0; width: 50%; text-align: right; /* depends on element width */ }

Issues With This Method

When an AP element is placed using the right property, an effect known as the 1px Rounding Error (http://www.communitymx.com/abstract.cfm?cid=A47F91175DB7863B) can occur, causing the AP element to be placed 1px to the left of its correct position. This won't matter if only text is involved, but if the AP element has borders or a background and is designed to fit precisely against the right container edge, it may be a problem.
Note: While IE5/Mac will generally position elements correctly at the right side of the viewport, the browser will show a mysterious and unneeded horizontal scrollbar. Testing by others has uncovered a "secret right margin" on absolutely positioned elements. There are several methods to defeat this problem. You can read more about it, and ways to overcome it at Philippe Wittenbergh's Mac IE 5 test page (http://www.l-c-n.com/IE5tests/right_pos/) about right positioning.

The top property can be used for exact vertical control, or it may be omitted. When this is done, the uncoded/unwritten value for top defaults to auto, placing the element directly below any previous flowed element that precedes it in the source. Also, remember that these AP elements aren't really "inside" the container, but rather are stacked over it, so if content within them causes them to become taller they may protrude below the bottom of the container. This is one good reason to avoid excessive use of absolute positioning on a page, when simply flowing the content can do the job better and more safely. If you are wondering what sort of widths on the AP elements are best, then stop wondering and just do some experimentation. Any widths will work, depending on the desired look. Sometimes pixels are fine, sometimes percentages, or ems can come in handy. The two items don't need to have the same width units either. You could have percentage on one side and em on the other. Playing with the variables is often the best way to get the layout looking good.

3 of 6

The "Floated" Method


Like absolute elements, floats can also be placed to the sides of a container, but the coding and methods are very different, as are the effects. AP elements have no impact on flowed content and are placed via a coordinate system, while floats do control where inline content outside the float is displayed, and are themselves placed according to their order in the source code and their direction or float value. For details on these CSS behaviors, see Flowing and Positioning (http://www.communitymx.com/abstract.cfm?cid=EA1A82A6F65A33F5) and Float: The Theory (http://www.communitymx.com/abstract.cfm?cid=A46708877E1AC008) . The arrangement is simply a container with two elements nested inside, each being floated, one left and the other to the right. Again, depending on the widths given to the floats, you may need to align inline content to the right. Note that either float may come first in the source. The code looks like this:

The HTML: <div class="container"> <div class="left-element"> Content in left item </div> <div class="right-element"> Content in right item </div> </div>

The CSS: .container {no required styles} .left-element { float: left; width: 49%; } .right-element { float: right; width: 49%; text-align: right; /* depends on element width */ }

4 of 6

Issues With This Method

If there is not enough room for the two floats to fit side by side, they will not just overlap, as AP elements do. Instead, floats wrap, forcing the float that comes second in the source to drop below the first float. Because of this, it is critical that the floats be prevented from coming into contact with one another. This is done by carefully controlling the float widths. Be sure to watch out for added padding and borders that increase the size of the floats. In some cases, these added properties can increase the size of the floats enough to cause wrapping. Unlike absolute positioning, the float method does not require that the container be positioned, nor is it strictly necessary to give the floats widths, since all the newer browsers "shrink-wrap" floats around their contents. Even IE/win back to IE5 does this. Unfortunately, IE5/Mac does not, so when shrink-wrapping is desired, it may be necessary to give a width only to IE5/Mac, hiding the width from all other browsers. Here's how it may be done:
.left-element {float: left;} .right-element {float: right;}

*>html .left-element {width: 49%;} *>html .right-element {width: 49%;}

The second pair of rules supplements the first two, but the construction of the selectors prevents any browser other than IE/Mac from recognizing the selectors. The selector construction says: "Select any element with a class attribute of .leftelement when it is nested within HTML, and HTML is the direct child of any other element." It so happens that IE browsers (both Mac and Win) believe there is some kind of mystery element wrapped around the HTML element. This is strange because HTML is supposed to be the primary or root element. Thus, IE browsers obey, and all others ignore the rule. Also, since the > (child) combinator is used in the selector, and IE/Win does not support that combinator, the result is that only IE/Mac obeys the rule. Going "widthless" on the floats will let the floats shrink to the size of the content, but if that content is a lengthy text, then line breaks must be added or the float will stretch as wide as the text line can go, possibly interfering with the other float. If widths are used, they may be in pixels, percentages, or ems. If percentage is used, don't give the floats each a 50% width. If the 1px rounding error should occur and the total width is 100%, then a dropped float will result. Better to leave some wiggle room. Giving a text float a pixel width works fine, but if it is to be just one line and the text sizing is bumped up by the user, then the single line may become too wide for the assigned pixel width and will wrap to a second line. This fate may be prevented by giving the float a width in ems rather than pixels, because an em width will enlarge along with the text. Sometimes the rate of enlargement is not exactly the same, so experimentation may be necessary to achieve satisfactory results.

5 of 6

Mix And Match


These basic techniques are not all-or-nothing methods, but may be joined or blended in various ways to get the desired page appearance. However, nothing is certain when dealing with real world layouts. These techniques may need to be "adjusted" when used on an actual page. Once you know how this stuff is done, it becomes easier to rearrange the methods, widths, and other variables to solve most design problems. It's actually kind of fun when the pieces start to fall into place. Approximate download size: 183k

Keywords CSS, align elements, absolute positioning, float, align elements left and right, CSS task

All content CommunityMX 2002-2004. All rights reserved.

6 of 6

Potrebbero piacerti anche