Tuesday, 30 September 2008
WSS3.0: Wrap Sharepoint Menu Items with custom HTML
DynamicItemFormatString="<li>{0}</li>"
Tuesday, 9 September 2008
CSS: Tips from Paul Sweatte
Only block level elements have margin and padding
Use even numbers to avoid covering 99% of the page
Use margin:0 auto and width:980px to center all container divs
Avoid using absolute or relative positioning on main content divs
Use a fixed width for all relatively positioned text to make sure it does not overflow its parent div or become truncated
Use block level tags around all inline elements so that no inline elements are a direct child of the container divs. Remember to set the dimensions of the inner blocks to be less than the dimensions of the container divs.
Use position:relative and left:xxx(where xxx is equal to the remaining space between the start of column and the edge of the window) to remove the space between the rightmost column of the layout and the body.
Use margin-left:xxx(where xxx is the same as above) as well as margin-right:yyy(where yyy is the minimum value needed to make the column visible) to achieve the same effect
Use position:relative when attempting to move elements within a container without moving any neighboring elements instead of using margin and padding adjustments
Use visibility:hidden instead of display:none to create a placeholder for unseen elements
Use display:block or vertical-align: bottom on images inside tables to avoid extra whitespace
Use display:table, display:inline-block, or display:compact instead of floats to align block level elements horizontally
Use display:block and set both width and padding values to align inline elements vertically and to align wrapping text and links
Use margin: 0 auto on elements with a width defined in pixels to center block level tags horizontally
Specify the line height to be the same as the height of the containing element to vertically center inline text
Use margin-top: xxx (where xxx is equal to the height of the container div minus the height of the centered element). Divide this value by two to vertically center a block element
Use margin-left: xxx (where xxx is equal to the width of the container div minus the width of the centered element). Divide this value by two to horizontally center a block element.
Use top: 50% and margin-top: -xxx(where -xxx is equal to half of the defined height in pixels) to center absolutely positioned content vertically
Use left: 50% and margin-left: -xxx(where -xxx is equal to half of the defined width in pixels) to center absolutely positioned content horizontally.
You may have to adjust the calculated margin-left values by about 10 pixels in IE specific styles sheets or conditional comments to account for box model differences.
Use position: absolute; bottom: 0; as well as the following steps to align a footer div with the end of a page at any resolution. Next create a container div that is the parent of every other div with position: relative; min-height: 100%; height: 100%. Then set the html and body tags to height:100%. Finally, add bottom padding to the main content div and margin-bottom:-xxx (where -xxx is equal to the height of the footer) to separate it from the footer. The padding may differ between IE and other browsers, so use a separate style sheet or conditional comments if necessary.
Use position:relative with left/right/top/bottom adjustment instead of floats for better cross browser consistency when laying out container elements
Use position:absolute or position:relative with margin adjustments instead of static positioning padding adjustments for better cross browser consistency when laying out content
Use absolute positioning to show important content(Headers, Breaking News) before the rest of the relative content loads
Create space on the page for absolute content by applying margins for the static content which is greater than the width or height of the absolute content
Use absolute positioning with margin shifting to reposition a class of elements (menu titles, footer text, gallery links) at once without giving them the same coordinates
Use vertical-align to center images and text on the same line. Don’t use the sub, super, text-top, or text-bottom values for cross browser consistency
Use list-style-type:none for a >ul< element, display:inline for its >li< elements, and add right side padding or margin for the >a< or >span< tags within to create a horizontal list that can used for tabs, menus, thumbnails, screenshots, etc.
Use display:table for the container div, display:table-row for the parent div, and display:table-cell for the nested divs to create rows and columns in standards compliant browsers.
Use the display:table-cell divs as a container to divide a large row into multiple div blocks for any column
Use display:block for the container div and parent div plus display:inline and zoom:1 for the nested divs to create rows and columns in IE6.
Use display:-moz-inline-box; and display:inline-block; for the container divs to create grids that don’t require zoom:1 or display:table. Remember to still use display:inline for the nested divs to support IE6.
Use vertical-align:top with display:-moz-inline-box to display content consistent with the behavior of display:inline-block on other browsers
If you use overflow:hidden with -moz-inline-box, set a fixed width for the container.
Use display: -moz-inline-box; -moz-box-orient:vertical; to create an inline box with vertically aligned block level child elements
Use display: -moz-inline-block; to create a thumbnail gallery using list elements that wrap and align consistently without floats
Set display properties (text-align, vertical-align,etc)on the parent element if they do not work on the
element itself
Set both the left margin and left padding of the list elements and avoid line-height for consistent placement of bullets across browsers.
Never float two or more columns to the same side, put each pair of left and right floated elements in a wrapper div big enough to contain both elements and padding
Use margin-right:auto with margin-left:0 and text-align:left to left align an hr tag across browsers
Nest an absolute-positioned element within a relative-positioned container with set width and height to freely position a block within a certain area
Use table{caption-side:bottom;} to move a table caption below the table instead of the default position above the table
Use absolute positioning with percentages for the simplest, most consistent display of troublesome elements
Use ‘text-indent: 0′ on elements that are specified ‘display:inline-block’ to avoid inheritance issues
Specify the line height to be the same as the height of the box to align text vertically
Don’t use percentages for margins or borders
Vertical margins and text alignment only apply to block elements
The vertical-align only applies to inline and table-cell elements
Use divs instead of paragraphs when margins don’t take effect
Use position:relative on any elements which need to have a z-index value
If you want relatively positioned elements in one div to overlap relatively positioned elements in another div, you have to raise the z-index of the entire div, or combine the content into the one container div
If you want one element to paint on top of everything else, but you want a child of that element to be behind everything else, make that element the only relatively positioned element, then position the child with a negative z-index.
Typography
Never define font-size for an element without defining it’s line-height
Never use italics
(font-size + vertical padding + vertical margin)/line-height for each element must be a multiple of a baseline number
(font-size + vertical padding + vertical margin) * line-height gives you the total height of each row of text.
Use percentages for all fonts to allow for browser selectable sizing
Never set percentages directly on a tag, always reference an ID or class to avoid cascading issues
Use margins and the
Use a:first-line to set a specific line-height for links that wrap
Use percentages instead of px for cross browser consistency
Use text-decoration:none and list-style-type:none to remove bullets and underlines from links and lists respectively
Use text-transform to capitalize headers and section titles
Use p:first-letter to set a large font and create a literature style drop cap effect for paragraphs
Use list-style-type:decimal in the style sheet instead of changing UL to OL in the HTML to number list items
Use white-space:pre with a return after each letter to display text that reads vertically
Use white-space: -moz-pre-wrap; for Firefox, word-wrap: break-word; for IE, and white-space: pre-wrap for Opera and Safari to force wrapping on predefined text
Use the
Set generous bottom margins equivalent left and right margins for paragraph tags globally for create consistent and maintainable leading and gutter standards
Set wider left margins for list items and quoted text to facilitate hanging punctuation
Inline text needs the same font-size, line-height, vertical alignment, padding, border, margins and position values to line up consistently across browsers.
Dimensions
Use ems as the measurement for container divs, and find the number of ems equal to 100% of the page width to use as your baseline
Reduce margins instead of increasing padding for cross browser consistency
Avoid negative margins on nested divs for cross browser consistency
Avoid defining conflicting values(colors, width, height) for the adjacent margins or borders of neighboring elements
Avoid padding and borders on inline text for cross browser consistency
Inline elements cannot have a defined width unless the display:block property is set
Width and height only apply to block or absolutely positioned elements
Add display:block and 100% width/height to anchor tags within table cells or vertical lists to make the click/hover area expand to the width of the parent element
Add display:block and width/height to image tags to maintain placeholder blocks for missing image files
Never set width or height on the same module where borders and padding are defined. Width goes on the parent, and then borders and padding go on a width:auto child
Never use a measurement for the line-height property
Always set a width on floated elements and their child elements
Use paragraphs instead of divs when width and height don’t take effect
Box Model
Use overflow:hidden to avoid scroll bars within a div and the expanding box problem in IE
Use width: auto and overflow: visible on button elements to avoid extra padding in IE
Use overflow:auto to avoid scroll bars within a textarea in IE
Use the HTML 4.0 Transitional doctype to force quirks mode on all browsers
Use the HTML 4.01 Strict doctype to force strict on all browser except IE
In the W3C box model, element width excludes padding and borders
In the classic IE box model, element width includes padding and borders, giving extra spacing for most content
IE6 always stretches boxes to display overflow content, while other browsers do not
IE6 doesn’t implement overflow:visible correctly
Use -moz-box-sizing: border-box; to emulate the IE box model in Firefox. Use box-sizing: border-box; to emulate it in Safari and Opera
Use -ms-box-sizing: content-box; to emulate the W3C box model in IE.
To remove the horizontal scrolling bar, declare overflow-x: hidden; as a style for the body tag
Background Colors and Images
Use the opacity property to create a rollover effect instead of swapping images
Use the background-position property to move an image to one of the eight compass directions behind the foreground text or image
Use the background-position property to change the hover state of links with background images using CSS sprites
Use background:transparent for rollovers where the parent element includes the image in the hovered position
Use background-image instead of image tags for images that are not content related
Defining the width of a static box that follows a float makes IE6 display differently than any standards compliant browser.
Don’t bother with quotation marks around background image URLs.
Use a ridiculous line-height or negative margin along with overflow:hidden to hide text replaced by images
Don’t use ems as the measurement value to hide text
To use an image for an hr tag, wrap it in a div that uses the image as a background URL and set the hr to display:none
Visual Interaction
Use cursor:pointer to emulate the onmouseover event cursor change
IE6 supports the :active, :hover, :focus, :link, :visited link states
Use :active instead of onclick events and :hover instead of onmouseover events when possible
Use “a[href=www.mysite.com]” to target elements with specific attribute values(CSS2 Attribute Selector)
Use “ul > li{…}” instead of “ul li{…}” to only target the first level children of a tag instead of all nested descendants(CSS2 Child Selector)
Add absolutely positioned elements within link tags and reference them in hover definitions(ex. A:hover span{…}) to create rollover dropdown menus without Javascript
Use a:active, a:focus{outline:0;width:0;height:0;} to remove the dotted line around clicked links
Use img {border:none;} to remove the border around images
Use :link,:visited to style links without styling anchor tags.
Use cursor styles and image maps to extend the click area of links to cover the dimensions of their parent elements without using Javascript
Use rel=”external” for all external links and a[rel~="external"] { target-new: tab; } (CSS3 Attribute Selector) to open links in a new tab
Use { target-name: modal; } (CSS3 Attribute Selector) to open links in a modal box
Use matching light colors for the top and left border and matching dark colors for the bottom and right border of a link. On hover, flip the color pairs and relatively position the link down and to the right by one pixel to generate a simple 3D button effect.
Stylesheet Organization
Use a CSS Validator to ensure that typos and conflicting declarations aren’t causing bugs on your page
Define classes to style block level elements(.content) instead of using tag references by ID (#main p) to make them independent of their parent elements
Define body.classname for each customizable element and define a button in Javascript to dynamically switch classes for each applicable node once the DOM event is triggered
Avoid semicolons on the last style declaration to avoid accidentally typing the end bracket before the semicolon and generating an error
Use styles to set properties for tables instead of table tag attributes for cross browser consistency
Add subclasses for common needs, such as highlighting the first or last item in a list, hiding and showing comment text, emphasizing the current navigation selection, and switching star rating colors on and off
Add IDs for standard layout components, such as site title, site logo, breadcrumbs, navigation, sidebars, content, surveys, and edit/back/search buttons
Style fonts and colors for standard layout components first to avoid redundancy and use cascading
when defining nested elements
Reset styles at the beginning of the style sheet to overwrite inconsistent defaults across browsers
Remove redundant and obsolete styles when moving test code to production
Define hover, focus, and active(e.g. :link:hover, :visited:active, etc.) rules in the preceding order of operation to cascade the rules properly
Use classes instead of IDs for any code intended to work inside the sandbox of a third party API, since IDs may be stripped out to avoid conflicts
Debugging
Test in at least four browser engines (Gecko, Webkit, Trident, Presto) each time you make a change
to avoid massive debugging efforts at the “end” of a layout task
Create a copy of the template and remove all divs except the misaligned one and its adjacent divs to debug positioning issues
Remove margins from inner divs when debugging ignored positioning values in absolutely positioned divs
Remove all inline text and start with non-breaking space as the placeholder content to debug width and height issues
Set margin, padding, font-size, and border size to zero for debugging unseen inheritance issues
Use a separate style sheet for IE when absolutely positioned elements or margins are inconsistent with other browsers
Use obvious background colors to highlight misplaced or misaligned nested elements when debugging
inner divs
Layout Emulation
Use multicolumn list to emulate newspaper column layout for articles
Style the corners using four or five pixel high strips before and after the main content div. These strips are created using bold tags. Each bold tag should be styled as display:block; overflow:hidden;. Surronding each set of strips should be a bold container styled as display:block; background:transparent; font-size:1px;. Each one except the last bold tag should be 1 pixel in height. Each one except the first bold tag should have the same background color as the content div. The horizontal margin for each bold tag should equal the sum of the tag’s position plus the number of remaining tags, plus one. This will produce rounded corners.
Use an alternative style sheet if no visited cookie exists for your site to load the home page with just the logo, set the visited cookie, and links to the standard style sheet which reveals the hidden content as an alternative to the traditional Flash based splash page
the main page to the splash page and the rest of the page’s content was hidden.
Sysadmin: FTP Commands
List of FTP commands for the Microsoft command-line FTP client
Command-line options
As you're starting the program from a DOS prompt:ftp [-v] [-d] [-i] [-n] [-g] [-s:filename] [-a] [-w:windowsize] [computer]
- -v - Suppresses verbose display of remote server responses.
- -n - Suppresses auto-login upon initial connection.
- -i - Turns off interactive prompting during multiple file transfers.
- -d - Enables debugging, displaying all ftp commands passed between the client and server.
- -g - Disables filename globbing, which permits the use of wildcard chracters in local file and path names.
- -s:filename - Specifies a text file containing ftp commands; the commands will automatically run after ftp starts. No spaces are allowed in this parameter. Use this switch instead of redirection (>).
- -a - Use any local interface when binding data connection.
- -w:windowsize - Overrides the default transfer buffer size of 4096.
- computer - Specifies the computer name or IP address of the remote computer to connect to. The computer, if specified, must be the last parameter on the line.
Client commands
- ! - Runs the specified command on the local computer
- ? - Displays descriptions for ftp commands
- append - Appends a local file to a file on the remote computer
- ascii - Sets the file transfer type to ASCII, the default
- bell - Toggles a bell to ring after each file transfer command is completed (default = OFF)
- binary - Sets the file transfer type to binary
- bye - Ends the FTP session and exits ftp
- cd - Changes the working directory on the remote computer
- close - Ends the FTP session and returns to the command interpreter
- debug - Toggles debugging (default = OFF)
- delete - Deletes a single file on a remote computer
- dir - Displays a list of a remote directory's files and subdirectories
- disconnect - Disconnects from the remote computer, retaining the ftp prompt
- get - Copies a single remote file to the local computer
- glob - Toggles filename globbing (wildcard characters) (default = ON)
- hash - Toggles hash-sign (#) printing for each data block transferred (default = OFF)
- help - Displays descriptions for ftp commands
- lcd - Changes the working directory on the local computer
- literal - Sends arguments, verbatim, to the remote FTP server
- ls - Displays an abbreviated list of a remote directory's files and subdirectories
- mdelete - Deletes one or more files on a remote computer
- mdir - Displays a list of a remote directory's files and subdirectories
- mget - Copies one or more remote files to the local computer
- mkdir - Creates a remote directory
- mls - Displays an abbreviated list of a remote directory's files and subdirectories
- mput - Copies one or more local files to the remote computer
- open - Connects to the specified FTP server
- prompt - Toggles prompting (default = ON)
- put - Copies a single local file to the remote computer
- pwd - Displays the current directory on the remote computer (literally, "print working directory")
- quit - Ends the FTP session with the remote computer and exits ftp (same as "bye")
- quote - Sends arguments, verbatim, to the remote FTP server (same as "literal")
- recv - Copies a remote file to the local computer
- remotehelp - Displays help for remote commands
- rename - Renames remote files
- rmdir - Deletes a remote directory
- send - Copies a local file to the remote computer (same as "put")
- status - Displays the current status of FTP connections
- trace - Toggles packet tracing (default = OFF)
- type - Sets or displays the file transfer type (default = ASCII)
- user - Specifes a user to the remote computer
- verbose - Toggles verbose mode (default = ON)
Sunday, 7 September 2008
Persits ASPEmail: Server object error 'ASP 0177 : 800401f3'
Problem Description
When trying to create an instance of a Persits component, the line of codeSet obj = Server.CreateObject("Persits.
") generates the following error (Windows NT/IIS4)
Server object error 'ASP 0177 : 800401f3'
Server.CreateObject Failed
Invalid class stringOn Windows 2000/IIS5, the error message is
Server object, ASP 0177 (0x800401F3)
Invalid ProgID.
Solution
This error means that either the component has not been registered on the server or the ProgID passed to the Server.CreateObject method is misspelled. On Windows 2003 and XP, it may also mean a permission problem on a system registry key.Make sure the component DLL is present on the server. The exact physical location of the DLL is not important. To register the component on the server, open MS DOS prompt and type
c:\> regsvr32 c:\path\aspupload.dll
(you must use your component's appropriate path and file name).
The correct Persits component ProgID's and file names are listed in the following table:
Name File ProgID AspEmail aspemail.dll "Persits.MailSender" AspEncrypt aspencrypt.dll "Persits.CryptoManager" AspGrid aspgrid.dll "Persits.Grid" AspJpeg aspjpeg.dll "Persits.Jpeg" AspUpload aspupload.dll "Persits.Upload" AspUser aspuser.dll "Persits.AspUser" XUpload xupload.ocx "Persits.XUpload" AspPDF asppdf.dll "Persits.PDF" On Windows 2003 and XP, this error may also mean the component's ProgID key in the system registry has been assigned insufficient permissions. Run regedt32, open the key HKEY_CLASSES_ROOT\ProgID, select Permissions from the Edit menu, and grant the "Everyone" account Full Control over the key. See the table above for the correct ProgID values.
Friday, 5 September 2008
WSS3.0: Enable quicklaunch on webpart pages
When you create a new Web Part Page within SharePoint 3.0 (Site Settings >
Create > Web Part Page) the Quick Launch Bar does not appear.
This to me is silly, because you spend time creating a nice menu, but it
doesn't appear on all pages.
So to ensure the Quick Launch Bar appears on all pages, including any newly
created Web Part pages, you need to open the SharePoint 3.0 site in
SharePoint Designer, open the Master Page and locate these 2 Content
Placeholders.
runat="server">"CODE"
For the record, you have a Master Page and you have many Content Pages.
Now the way it works as I see it, the Master Page has all the Quick Launch
code nestled in these content placeholders, and the Quick Launch is only
visible to the Content Pages which ask it to be visible.
You could go and manipulate the actual Web Part Page (which is already
created) and force it to show the Quick Launch Bar, but what happens when a
non-technical user goes and creates a new Web Part Page? They will have to
call the developer and ask them to manipulate the page to get the Quick
Launch to show up, which is not a good plan.
My plan was to manipulate the Master Page and force the Quick Launch Bar to
show up on every page. Even new Web Part Pages (that get created by
non-technical users).
So here’s what I did:
Find the Quick Launch CODE that is nestled within the first Content
Placeholder stated above. Now find the Closing Content Placeholder Tag for
this CODE and move it to the top of the Quicklaunch CODE. So the Content
place holder will look like
runat="server">
And the Quick Launch CODE is outside of the Content Placeholder tags. This
now forces the Quick Launch to show up on every page. Bloody simple aye.
You are not quite finished yet because the Quick Launch width shrinks a
little bit and the words wrap to the next line.
So now find the second content Placeholder stated above, and do the same
thing as you did for the previous CODE.
NOTE:
DO NOT delete the Content Placeholders, as they are still needed to render
(load) the page. The page will error if they are deleted.
I have not encountered any issues in doing this yet, but remember, when
using SharePoint designer you can always revert to the original Master Page
if things go pear shaped.
Ref : http://www.eggheadcafe.com/software/aspnet/29440009/show-quick-launch-on-webp.aspx
Thursday, 4 September 2008
CSS: IE and Firefox Hacks
.hello {
text-align: center;
background-color: #FF0000;
*background-color: #00FF00;
_background-color: #0000FF;
}
If you are familiar with CSS you'll understand all of the syntax except
for the "*" and "_" in front of the background-color properties. What
do they do?
The CSS specs say that browsers should read any
property names they know about and ignore any property names they don't
know about. In the above CSS the spec compliant browsers know about a
property named "background-color" but don't know about properties named
"*background-color" and "_background-color".
To cut a long story
short, the Internet Explorer CSS parser is overly aggressive at trying
to discover the names of properties and will in fact ignore leading
non-alphanumeric characters. From my testing this appears to be the
case from at least IE5 onwards.
It became convention amongst web
developers to used an underscore in front of property names when
targeting CSS for IE, although any non-alphanumeric character will
work. However, the CSS 2.1 spec made underscore a valid character in a
property name, so IE7 specifically removed underscore from their
aggressive parsing. From IE7 onwards web developers have been using an
asterisk instead of an underscore when targeting CSS at IE, although
any non-alphanumeric character will do. Interestingly, the removal of
the underscore hack in IE7 allows you to target CSS at pre-IE7 (using
underscore) and post-IE7 (using asterisk or some other non-alphanumeric
character) browsers.
So with this background knowledge here is how the above CSS would be interpreted by different browsers:
* Firefox, Opera, Safari and all non-IE browsers would correctly parse "background-color", fail to parse "*background-color" and "_background-color", and will set the background color of the div with class "hello" to red.
* IE6 and earlier versions of IE will successfully parse "background-color", "*background-color" and "_background-color". The background color value will come from the last successfully parsed property, so the background color of the div with class "hello" will be set to blue.
* IE7 and later versions of IE will successfully parse "background-color", "*background-color" but fail to parse "_background-color". The background color value will come from the last successfully parsed property, so the background color of the div with class "hello" will be set to green.
One final note on this IE leading non-alphanumeric character hack: It is invalid CSS so the strictest parsers will give you an error.
Firefox CSS Hacks
There are plenty of CSS hacks for IE, but what about Firefox?
I've found one hack that allows you to target Firefox 2 or Firefox 3, but some versions of IE also pick up the CSS intended for Firefox. Extending our CSS file above:
.hello {
text-align: center;
background-color: #FF0000;
*background-color: #00FF00;
_background-color: #0000FF;
}
/* Target Firefox 3 */
.hello, x:-moz-any-link, x:default {
background-color: #FFFFFF;
}
/* Target Firefox 2 */
.hello, x:-moz-any-link {
background-color: #FF00FF;
}
In Firefox 2 the background color of the div with class "hello" will be
pink, but strangely it will also be pink in IE5 and IE7 (they will pick
up the last CSS property intended for Firefox), and blue in IE5.5 and
IE6 (they don't pick up the CSS intended for Firefox).
If you find any Firefox CSS hacks that will only be applied to Firefox please let me know.
REF: http://robertmaldon.blogspot.com/2008/03/css-tricks-that-target-specific.html
Google: Chrome Browser easter eggs
Persits ASPEmail: Read Receipts
Monday, 1 September 2008
CSS: CSSP ie CSS Positioning
Web design usually means something more than just fonts, colours and
graphical elements. It also implies some sort of layout. A web designer has
three available tools for creating a layout:
* tables,
* floats,
* positioning.
Layout tables belong in the last millennium. Floats are often the best
solution, especially when you don't know in advance which column will be the
longest. Older browsers, and Internet Explorer, aren't too good at dealing with
floats, though. Besides, that's a separate topic.
Positioning is perhaps one of the most misunderstood parts of
CSS 2. Let us look a little closer at how it works.
This article is now available in Polish: Bezwzględnie względny, in Spanish: Relativamente Absoluto, in Turkish: CSS Hizalama, and in Dutch: Relatief, absoluut
Absolute positioning is sometimes referred to as CSS-P.
Beginners using Dreamweaver tend to call it layers, which is
unfortunate, because it can be confused with Netscape's proprietary
But let's start from the beginning. The position
property in CSS accepts four different values (plus
inherit):
* static,
* relative,
* absolute,
* fixed.
For all values except static we can affect the element's
position through the top, bottom, left
and right properties.
Static Positioning
Elements with position:static, which is the default value for
all elements, are not positioned at all. Their placement on the canvas is
determined by where they occur in the document.
Thus the static value is only used for overriding a
previously set value.
We will use the term "statically positioned" in this article, even
though it isn't fully correct.
Relative Positioning
Elements with position:relative are positioned relative to
themselves. This may sound strange, but it can be useful sometimes.
If we specify a value for either of the four edge properties, the relatively
positioned element is shifted in relation to the position it would have occupied
if it had been statically positioned.
This may sound like Greek to you, but it's actually quite logical. If we just
set position:relative on an element, without specifying any of the
edge properties, the element ends up exactly where it would have been if we had
set position:static, or if we hadn't set position at
all.
If we set top:10px, the element is shifted 10 pixels from its
original top edge. That means it moves downward. A negative value shifts the
element in the opposite direction, so we could achieve the exact same result by
setting bottom:-10px. This means it's not meaningful to specify
both top and bottom, or both left and right. There may, however, be reasons for
specifying, for instance, top and left together, if we
want to shift an element both vertically and horizontally.
Now, this isn't very useful for creating columns, because a relatively
positioned element remains in the document flow – in the position where it
originally was. It still takes up space, but not where it's actually shown, but
where it would have been shown, had it been statically positioned.
What does this mean in the real world? Relative positioning is mostly useful
for shifting an element a few pixels in either direction, or you'll get a
"hole" in your page. There is, however, another use for it that is much
more important: A relatively positioned element counts as positioned, even if we
don't shift it a single pixel in any direction. We will soon see why that is
important.
Absolute Positioning
What people normally mean by positioning, CSS-P or layers, is
elements with position:absolute. The top,
bottom, left and right properties specify
the distance to the corresponding edge of the element. But from what?
Ironically, absolute positioning is relative. Yes, you read that right. An
absolutely positioned element is positioned relative to another element, called
the containing block. Here comes the definition of that. Take a few
deep breaths and hold on tight to the armrests of your chair.
The containing block of an absolutely positioned element is its nearest
positioned ancestor, or, if there is no such element, the document's
initial containing block.
By "positioned ancestor" we mean a structurally superior element whose
position property is absolute, fixed or
relative. So here is that important use for relatively positioned
elements that we touched on a minute ago. By setting
position:relative for an element, without shifting it at all, we
can establish a new context for its absolutely positioned children. Sounds easy,
doesn't it?
But if there is no positioned ancestor then? That's where the so-called
initial containing block comes into the picture. The CSS
standard helpfully says that this is "chosen by the user agent". ("User
agent" is the application that processes a web page, for instance a browser,
some assistive technology, or a search engine.) The standard also states that it
could be related to the viewport. In practice this means either of the
BODY or HTML elements.
Absolutely positioned elements are completely removed from the document flow.
This means they don't take up any space. Or, to phrase it differently, they
don't affect subsequent elements. We thus have to make sure ourselves that no
other content ends up underneath our positioned element, unless that is the very
effect we're after, of course.
An absolutely positioned element with top:100px is consequently
placed so that its top edge is 100 pixels from the top edge of its containing
block. In browsers that support CSS you can specify all four edges
and let the browser compute the width and the height. Unfortunately this doesn't
work in Internet Explorer, so it's almost always necessary to specify at least
the width of an absolutely positioned element.
It is perfectly legal to specify negative values for the edge properties, but
if you do, you should be very aware of what the containing block is. Otherwise
you risk putting the element completely or partially off the screen.
Fixed Positioning
We established earlier that absolute positioning is relative, so it should
come as no surprise that fixed positioning is absolute.
An element with position:fixed is positioned absolutely with
respect to the viewport (the browser window). Fixed positioning is very similar
to absolute positioning, but there are differences. The position is always
computed with respect to the viewport; the viewport is always the containing
block. The element is removed from the document flow and it stays put even if
the user scrolls the document.
Unfortunately Internet Explorer doesn't support fixed positioning. There are
a number of more or less complicated ways to circumvent that, but fixed
positioning isn't actually as useful as one may think. Sure, it's conceivable to
have a menu in the left or right column that is always visible, but most users
today expect everything on the page to move upwards when they scroll.
Finally
Absolute positioning is useful for multi-column layouts, as long as you
always know which column is longest. Since the absolutely positioned elements
are removed from the document flow, the don't affect subsequent elements.
Therefore it is very difficult to have a full-width footer appear after all the
columns.
As with any web design, you should try to use relative units with
positioning, so that the layout can adapt to different window sizes. The value
for left, for instance, should be specified in em or
%, not in px.
If you specify the width for an absolutely positioned element, either
explicitly via width in percents, or implicitly
via left and right, the standard says that it should
be computed relative to the containing block. Both Internet Explorer
and Opera get this wrong, unfortunately, and use the width of the
parent element as the basis for their computations. Gecko-based
browsers like Mozilla and Firefox behave correctly.
With all types of positioning, including relative, you should set margins and
padding explicitly, especially if you want it to look the same cross-browser.
Browsers have different standard values for these properties.
When positioned elements overlap, we can control the stacking order with the
z-index property. The higher the z-index, the closer
to the user the element ends up. Unfortunately this isn't quite as
straightforward as it sounds, since each containing block establishes its own
context for z-index. So to put one element on top of another
element, with a different containing block, you need to increase the
z-index for the first element's containing block. In
really complex layouts you can find yourself in impossible situations, if you
want to stack three elements where the middle one has a different containing
block than the other two. As far as we know, this cannot be done.
Absolute positioning is often used with DIV elements, but it's
perfectly valid to position any element.