CSS Positioning

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

h FRONTEND g

CSS Positioning

h FRONTEND g

The CSS Box Model


Every Element In Web Design Is A Rectangular Box.
The margin is in the white. Margin is unique in that it doesn't aect the size of the box itself per-say, but it aects other content interacting with the box, and thus an important part of the CSS box model.

The size of the box itself is calculated like this:

Width: width + padding-left + padding-right + border-left + border-right Height: height + padding-top + padding-bottom + border-top + border-bottom

What if these values are undeclared?


If padding or borders are undeclared, they are either zero (likely if using a css reset1 ) or the browser default value (probably not zero especially on form elements that are commonly not reset).

a CSS reset removes default styling from page elements so that you are "starting fresh" with the attributes you choose to apply. This is important for two reasons. One, puts all browsers on a level playing field. Different browsers apply different default styling to elements, so if you are looking to have your website look the same in all the different browsers (you are), a CSS reset is important. Two, it allows you to "think forwards" as far as applying attributes like margin and padding to page elements. Instead of having to "think backwards" in removing attributes from elements, you can only apply them to elements you know need them. 2

h FRONTEND g

If the width of a box is undeclared (and the box is a block level element), things get a little weirder. Let's start with that, and then move on to some other good-to-know stu about the box model.

The Default Width of Block Level Boxes


If you don't declare a width, and the box has static or relative positioning, the width will remain 100% in width and the padding and border will push inwards instead of outward. But if you explicitly set the width of the box to be 100%, the padding will push the box outward as normal.

The lesson here being that the default width of a box isn't really 100% but a less tangible "whatever is left". This is particularly valuable to know, since there are lots of circumstances where it is immensely useful to either set or not set a width. The biggest ass-biter I always nd with this is text area elements, which very much need their widths set to ght the required "cols" attribute, and are unable to have children elements. So you often need the text area to be explicitly set to 100%, yet have padding as well, pushing it too large to t. In a static width environment, we often resort to pixel widths that t, but no such luck in uid width environments.
3

h FRONTEND g

Absolute Boxes with No Width


Absolutely positioned boxes that have no width set on them behave a bit strangely. Their width is only as wide as it needs to be to hold the content. So if the box contains a single word, the box is only as wide as that word renders. If it grows to two words, it'll grow that wide.

This should continue until the box is 100% of the parent's width (the nearest parent with relative positioning, or browser window) and then begin to wrap. It feels natural and normal for boxes to expand vertically to accommodate content, but it just feels strange when it happens horizontally. That strange feeling is warranted, as there are plenty of quirks in how dierent browsers handle this, not to mention just the fact that text renders dierently across platforms.

h FRONTEND g

Floated Boxes With No Width


The same exact behavior is seen with oated elements with no widths. The box is only as wide as it needs to be to accommodate the content, up to as wide as it's parent element (doesn't need to be relatively positioned though). Because of the fragile nature of these width-less boxes, the lesson to take away here is to not rely on them in mission-critical scenarios, like in overall page layout. If you oat a column to use as a sidebar and count on some element inside (like an image) to be responsible for holding it's width, you are asking for trouble.

Inline Elements are Boxes Too


We've been kind of focusing on boxes as block-level elements here. It's easy to think of block-level elements as boxes, but inline elements are boxes too. Think of them as really really long and skinny rectangles, that just so happen to wrap at every line. They are able to have margin, padding, borders just like any other box.

The wrapping is what makes it confusing. A left margin as shown above pushes the box to the right as you would suspect, but only the rst line, as that is the beginning of the box. Padding is applied above and below the text like it should be, and when it wraps it ignores the line above its padding and begins where the line-height dictates it should begin. The background was applied with transparency to see how it works more clearly.

The best thing to do is always set a width on anything floated, absolutely positioned, or fixed positioned to avoid cross browser problems.
5

h FRONTEND g

CSS Positioning
1 position: static
The default positioning for all elements is position:static, which means the element is not positioned and occurs where it normally would in the document. Normally you wouldn't specify this unless you needed to override a positioning that had been previously set.

#div-1 { position:static; }

2 position: relative
If you specify position:relative, then you can use top or bottom, and left or right to move the element relative to where it would normally occur in the document. Let's move div-1 down 20 pixels, and to the left 40 pixels:
#div-1 { position:relative; top:20px; left:-40px; }
6

h FRONTEND g

Notice the space where div-1 normally would have been if we had not moved it: now it is an empty space. The next element (div-after) did not move when we moved div-1. That's because div-1 still occupies that original space in the document, even though we have moved it.

3 position: absolute
When you specify position:absolute, the element is removed from the document and placed exactly where you tell it to go. Let's move div-1a to the top right of the page:

h FRONTEND g

#div-1a { position:absolute; top:0; right:0; width:200px; }

Notice that this time, since div-1a was removed from the document, the other elements on the page were positioned dierently: div-1b, div-1c, and div-after moved up since div-1a was no longer there. Also notice that div-1a was positioned in the top right corner of the page. It's nice to be able to position things directly the page, but it's of limited value. What I really want is to position div-1a relative to div-1. And that's where relative position comes back into play. 2

4 position: relative + position: absolute


If we set relative positioning on div-1, any elements within div-1 will be positioned relative to div-1. Then if we set absolute positioning on div-1a, we can move it to the top right of div-1:
#div-1 { position:relative; } #div-1a { position:absolute; top:0; right:0; width:200px; }

2 There is a bug in the Windows IE browser: if you specify a relative width (like "width:50%") then the width will be based on the parent element instead of on the positioning element. 8

h FRONTEND g

5 two column absolute


Now we can make a two-column layout using relative and absolute positioning!

#div-1 { position:relative; } #div-1a { position:absolute; top:0; right:0; width:200px; } #div-1b { position:absolute; top:0; left:0; width:200px; }

h FRONTEND g

One advantage to using absolute positioning is that we can position the elements in any order on the page, regardless of the order they appear in the HTML. So I put div-1b before div-1a. But wait - what happened to the other elements? They are being obscured by the absolutely positioned elements. What can we do about that?

6 two column absolute height


One solution is to set a xed height on the elements. But that is not a viable solution for most designs, because we usually do not know how much text will be in the elements, or the exact font sizes that will be used.
#div-1 { position:relative; height:250px; } #div-1a { position:absolute; top:0; right:0; width:200px; } #div-1b { position:absolute; top:0; left:0; width:200px; }

10

h FRONTEND g

float

For variable height columns, absolute positioning does not work, so let's come up with another solution. We can "oat" an element to push it as far as possible to the right or to the left, and allow text to wrap around it. This is typically used for images, but we will use it for more complex layout tasks (because it's the only tool we have).
#div-1a { float:left; width:200px; }

7 float columns
If we oat one column to the left, then also oat the second column to the left, they will push up against each other.
#div-1a { float:left; width:150px; } #div-1b { float:left; width:150px; }

11

h FRONTEND g

8 float columns with clear


Then after the oating elements we can "clear" the oats to push down the rest of the content.
#div-1a { float:left; width:190px; } #div-1b { float:left; width:190px; } #div-1c { clear:both; }

12

h FRONTEND g

How do they differ?


Every single element on a web page is a block. This is easy to understand when when you set the element to display: block; or if that element is by default display: block; This means you can set a width and a height and that element will respect that. But elements that are display: inline, like a span by default, are also rectangles, they just ow onto the page dierent, lining up horizontally as they can.

Static.
This is the default for every single page element. Dierent elements don't have dierent default values for positioning, they all start out as static. Static doesn't mean much, it just means that the element will ow into the page as it normally would. The only reason you would ever set an element to position: static is to forcefully-remove some positioning that got applied to an element outside of your control. This is fairly rare, as positioning doesn't cascade.

Relative
This type of positioning is probably the most confusing and misused. What it really means is "relative to itself". If you set position: relative; on an element but no other positioning attributes (top, left, bottom or right), it will no eect on it's positioning at all, it will be exactly as it would be if you left it as position: static; But if you DO give it some other positioning attribute, say, top: 10px;, it will shift it's position 10 pixels DOWN from where it would NORMALLY be. I'm sure you can imagine, the ability to shift an element around based on it's regular position is pretty useful. I nd myself using this to line up form elements many times that have a tendency to not want to line up how I want them to.There are two other things that happen when you set position: relative; on an element that you should be aware of. One is that it introduces the ability to use z-index on that element, which doesn't really work with statically positioned elements. Even if you don't set a z-index value, this element will now appear on top of any other statically positioned element. You can't ght it by setting a higher z-index value on a statically positioned element. The other thing that
13

h FRONTEND g

happens is it limits the scope of absolutely positioned child elements. Any element that is a child of the relatively positioned element can be absolutely positioned within that block.

A page element with relative positioning gives you the control to absolutely position children elements inside of it.

The relative positioning on the parent is the big deal here. Look what would happen if you forgot that:

Might not look like a big deal in this small example, but it really is a signicant change. What is happening is the absolutely positioned elements are positioning themselves in relation to the body element instead of their direct parent. So if the browser window grows, that one in the bottom left is going to stick with the browser window, not hang back inside like his well behaved brother from the rst image.

14

h FRONTEND g

Absolute
This is a very powerful type of positioning that allows you to literally place any page element exactly where you want it. You use the positioning attributes top, left bottom and right to set the location. Remember that these values will be relative to the next parent element with relative (or absolute) positioning. If there is no such parent, it will default all the way back up to the <html> element itself meaning it will be placed relatively to the page itself.The trade-o, and most important thing to remember, about absolute positioning is that these elements are removed from the ow of elements on the page. An element with this type of positioning is not aected by other elements and it doesn't aect other elements. This is a serious thing to consider every time you use absolute positioning. It's overuse or improper use can limit the exibility of your site.

Fixed
This type of positioning is fairly rare but certainly has its uses. A xed position element is positioned relative to the viewport, or the browser window itself. The viewport doesn't change when the window is scrolled, so a xed positioned element will stay right where it is when the page is scrolled, creating an eect a bit like the old school "frames" days.

15

h FRONTEND g

CSS Overflow
What happens when you do set a specic height or width on a box, and the content inside cannot t? That is where the CSS overow property comes in, allowing you to specify how you would like that handled. There are four values for the overow property: visible (default), hidden, scroll, and auto. There are also sister properties overow-y and overow-x, which enjoy less widespread adoption. Let's take a look at each and then discuss some common uses and quirks.

Visible
If you don't set the overow property at all, the default is visible. So in general, there is no reason to explicitly set this property to visible unless you are over-riding it from being set elsewhere.

16

h FRONTEND g

The important thing to remember here is that even though the content is visible outside of the box, that content does not aect the ow of the page. For example:

Generally, you shouldn't be setting static heights on boxes with web text in them anyway, so it shouldn't come up.

Hidden
The opposite of the default visible is hidden. This literally hides any content that extends beyond the box.

17

h FRONTEND g

This is particularly useful in use with dynamic content and the possibility of an overow causing serious layout problems. However, bear in mind that content that is hidden in this way is utterly inaccessible (short of viewing the source). So for example a user has their default font size set larger than you would expect, you may be pushing text outside of a box and hiding it completely from their view.

Scroll
Setting the overow value of a box to scroll will hide the content from rendering outside the box, but will oer scrollbars to scroll the interior of the box to view the content.

Of note with this value is that you get BOTH horizontal and vertical scrollbars no matter what, even if the content requires only one or the other.

18

h FRONTEND g

Auto
Auto overow is very similar to the scroll value, only it solves the problem of getting scrollbars when you don't need them.

Float Clearing
One more popular uses of setting overow, strangely enough, is oat clearing. Setting overow doesn't clear the oat at the element, it self-clears. This means that the element with overow applied (auto or hidden), will extend as large as it needs to encompass child elements inside that are oated (instead of collapsing), assuming that the height isn't declared. Like this:

19

h FRONTEND g

Cross Browser Concerns


Like most things in CSS, there are plenty of cross-browser quirks with overow. Here they are:

Scroll bars inside or outside of box?


Firefox puts them outside, IE puts them inside. I believe only IE actually gets this correct (it should be inside).

20

h FRONTEND g

Make sure to account for this substantial dierence.

IE 8 expanding box bug


There are lots of fun new bugs, including some very serious ones that hide entire web pages, with IE.

Breaking floated layouts


IE 6, 7 and 8 all screw up the default overow visible and will expand a box horizontally to t content (likely an image). This is especially painful for layouts built on oated columns, and a single expanded column can push other columns down and cause some pretty seriously borked layouts.

Can scroll bars be styled with CSS?


IE3 used to allow this in older versions of IE but it has since been discontinued. Like many form elements, scroll bars are not able to be styled through CSS. I don't have any particular opinion on if that's a good or bad thing, but I can say that having scroll bars all over the content of a website is ugly and gross. If you need a scrolling solution that is able to be styled, you may want to look to JavaScript.

3 IE displays a vertical scrollbar all the time whether it needs it or not. This can be nice for preventing horizontal jumps, but isn't always desirable. To remove this in IE, you can set overflow to auto on the body element. 21

h FRONTEND g

All About Floats


What is "Float"?
Float is a CSS positioning property. To understand its purpose and origin, we can look to print design. In a print layout, images may be set into the page such that text wraps around them as needed. This is commonly and appropriately called "text wrap". Here is an example of that.

In page layout programs, the boxes that hold the text can be told to honor the text wrap, or to ignore it. Ignoring the text wrap will allow the words to ow right over the image like it wasn't even there. This is the dierence between that image being part of the ow of the page (or not). Web design is very similar .

22

h FRONTEND g

In web design, page elements with the CSS float property applied to them are just like the images in the print layout where the text ows around them. Floated elements remain a part of the ow of the web page. This is distinctly dierent than page elements that use absolute positioning. Absolutely positioned page elements are removed from the ow of the webpage, like when the text box in the print layout was told to ignore the page wrap. Absolutely positioned page elements will not aect the position of other elements and other elements will not aect them, whether they touch each other or not. Setting the oat on an element with CSS happens like this:
#sidebar { float: right; }

There are four valid values for the oat property. Left and Right oat elements those directions respectively. None (the default) ensures the element will not oat and Inherit which will assume the oat value from that elements parent element.

What are floats used for?


Aside from the simple example of wrapping text around images, oats can be used to create entire web layouts.

Floats are also helpful for layout in smaller instances. Take for example this little area of a web page. If we use oat for our little avatar image, when that image changes size the text in the box will reow to accommodate:
23

h FRONTEND g

This same layout could be accomplished using relative positioning on container and absolute positioning on the avatar as well. In doing it this way, the text would be unaected by the avatar and not be able to reow on a size change.

Clearing the Float


Float's sister property is clear. An element that has the clear property set on it will not move up adjacent to the oat like the oat desires, but will move itself down past the oat. Again an illustration probably does more good than words do.

In the above example, the sidebar is oated to the right and is shorter than the main content area. The footer then is required to jump up into that available space as is required by the oat. To x this problem, the footer can be cleared to ensure it stays beneath both oated columns.
24

h FRONTEND g

#footer { clear: both; }

Clear has four valid values as well. Both is most commonly used, which clears oats coming from either direction. Left and Right can be used to only clear the oat from one direction respectively. None is the default, which is typically unnecessary unless removing a clear value from a cascade. Inherit would be the fth, but is strangly not supported in Internet Explorer. Clearing only the left or right oat, while less commonly seen in the wild, denitely has its uses.

The Great Collapse


One of the more bewildering things about working with oats is how they can aect the element that contains them (their "parent" element). If this parent element contained nothing but oated elements, the height of it would literally collapse to
25

h FRONTEND g

nothing. This isn't always obvious if the parent doesn't contain any visually noticeable background, but it is important to be aware of.

As anti-intuitive as collapsing seems to be, the alternative is worse. Consider this scenario:

If the block element on top were to have automatically expanded to accomodate the oated element, we would have an unnatural spacing break in the ow of text between paragraphs, with no practical way of xing it. If this were the case, us designers would be complaining much harder about this behavior than we do about collapsing. Collapsing almost always needs to be dealt with to prevent strange layout and crossbrowser problems. We x it by clearing the oat after the oated elements in the container but before the close of the container.

Techniques for Clearing Floats


If you are in a situation where you always know what the succeeding element is going to be, you can apply the clear: both; value to that element and go about your business. This is ideal as it requires no fancy hacks and no additional elements
26

h FRONTEND g

making it perfectly semantic. Of course things don't typically work out that way and we need to have more oat-clearing tools in our toolbox.

The Empty Div Method


It is, quite literally, an empty div. <div style="clear: both;"></div>. Sometimes you'll see a <br /> element or some other random element used, but div is the most common because it has no brower default styling, doesn't have any special function, and is unlikely to be generically styled with CSS. This method is scorned by semantic purists since its presence has no contexual meaning at all to the page and is there purely for presentation. Of course in the strictest sense they are right, but it gets the job done right and doesn't hurt anybody.

The Overflow Method


It relies on setting the overow CSS property on a parent element. If this property is set to auto or hidden on the parent element, the parent will expand to contain the oats, eectively clearing it for succeeding elements. This method can be beautifully semantic as it may not require an additional elements. However if you nd yourself adding a new div just to apply this, it is equally as unsemantic as the empty div method and less adaptable. Also bear in mind that the overow property isn't specically for clearing oats. Be careful not to hide content or trigger unwanted scrollbars.

The Easy Clearing Method


It uses a clever CSS pseudo selector (:after) to clear oats. Rather than setting the overow on the parent, you apply an additional class like "clearx" to it. Then apply this CSS:.
clearfix:after { content: "."; visibility: hidden; display: block; height: 0; clear: both; }

This will apply a small bit of content, hidden from view, after the parent element

27

h FRONTEND g

which clears the oat. This isn't quite the whole story, as additional code needs to be used to accommodate for older browsers. Dierent scenarios call for dierent oat clearning methods. Take for example a grid of blocks, each of dierent types.

To better visually connect the similar blocks, we want to start a new row as we please, in this case when the color changes. We could use either the overow or easy clearing method if each of the color groups had a parent element. Or, we use the empty div method in between each group. Three wrapping divs that didn't previously exist or three after divs that didn't previously exist. I'll let you decide which is better.

28

h FRONTEND g

Problems with Floats


Floats often get beat on for being fragile. The majority of this fragility comes from IE 6 and the slew of oat-related bugs it has. As more and more designers are dropping support for IE 6, you may not care, but for the folks that do care here is a quick rundown.

Pushdown
Is a symptom of an element inside a oated item being wider than the oat itself (typically an image). Most browsers will render the image outside the oat, but not have the part sticking out aect other layout. IE will expand the oat to contain the image, often drastically aecting layout. A common example is an image sticking out of the main content push the sidebar down below. Quick x: Make sure you don't have any images that do this, use overflow: hiddento cut o excess.

Double Margin Bug


Another thing to remember when dealing with IE 6 is that if you apply a margin in the same direction as the oat, it will double the margin. Quick x: setdisplay: inline on the oat, and don't worry it will remain a block-level element. The 3px Jog is when text that is up next to a oated element is mysteriously kicked away by 3px like a weird forceeld around the oat. Quick x: set a width or height on the aected text. In IE 7, the Bottom Margin Bug is when if a oated parent has oated children inside it, bottom margin on those children is ignored by the parent. Quick x: using bottom padding on the parent instead.
29

h FRONTEND g

Alternatives
If you need text wrapping around images, there really aren't any alternatives for oat. But for page layout, there denitely are choices.

30

You might also like