Documente Academic
Documente Profesional
Documente Cultură
In this tutorial you will learn about Cascading Style Sheets (CSS), Introduction to CSS, What you should
already know? History, What is CSS? CSS saves a lot of work and time, CSS reduces the file size of HTML
documents and CSS can be designed for different media
The tutorial assumes that you have basic understanding of the following topics:
• HTML/XHTML
History
In the old days we had only HTML, which was good, with HTML you can make good web designs, you can
adjust the layouts using tables, and the layout problems can be fixed using the single-pixel gif image, but
this is not good.
The layout problem and many others were fixed using CSS, with CSS design became a straight forward
process, all web development/design tools now contain a CSS designer that makes using CSS a first
choice for web designers.
What is CSS?
Single CSS file can control the appearance of multiple HTML documents; to make a change to all
documents you don’t have to make the change in every document, just make it in the CSS file, and it will
be reflected on all documents that are linked to it.
Even for one document, the CSS can define the appearance of an HTML element; all you have to do to
change the appearance of that element all over the document is to change it in the CSS, this saves a lot of
time and work.
By removing the presentation from the HTML documents and saving it in a smaller size CSS file, you get
rid of presentation attributes and spacing images which reduces the size of the document and makes site
navigation faster.
A document can be styled in a way that is suitable for the presentation media, you can have many style
sheets linked to one document, every sheet is for content presentation on a specific media, including
browsers, printers, handheld devices, and projectors.
Rule set
A rule or rule set tells the browser how to render an element, the rule set consists of the following:
Example:
The selector here is the HTML element < p >, all what follows is the declaration block, the declaration
block has to start with an opening curly brace “{“, and ends with a closing curly brace “}”, every
property/value pair has to be ended with a semi column”;”, the semi column can be only omitted for the
last property/value pair, the property and the value are separated with a colon “:”, spaces and line feeds
may be added for better readability, it doesn’t affect the CSS validity, the previous rule can be written as:
p
{
text-align: right;
color: red;
}
Combining selectors
When many selectors have the same declarations, they may be grouped, this will reduce the CSS file size,
and makes it easier to update the style.
Example:
h1, h2, h3
{
text-align: center;
color: red;
}
Example:
h1, h2, h3
{
text-align: center;
color: red;
}
h2
{
So all the elements h1, h2, and h3 will have center-aligned text, and red color, and only h2 font style will
be italic.
You can define different style for the same HTML element using the class selector.
Example:
td.header {
font-weight: bold;
font-variant: small-caps;
text-align: center;
}
td.normal {
text-align: left;
}
The tag name can be omitted too, this will enable any HTML element to use the rule, the previous CSS
rules can be written as:
.header {
font-weight: bold;
font-variant: small-caps;
text-align: center;
}
.normal {
text-align: left;
}
The id selector
You can define the same style for different HTML elements using the id selector.
Example:
#red
{
color: red;
p#red
{
color: red;
}
This way only the < p > element with id of red < p id=”red” > will be styled using this rule.
Comments
CSS comments can be placed anywhere in the CSS, it will be ignored by the browser, the comment has to
start with “/*” and ends with “*/”.
Example:
/* comment /
p
{
/ another comment /
text-align: right; / another comment */
color: red
}
There are different types for specifying styles to be used with HTML documents, they can be specified in
an external CSS file, inside the < head > element of the HTML document, or/and inline to be specific to a
single HTML element, also there is the browser default style.
These styles will be cascaded in a single HTML documents at the following priority:
1. Browser default.
.
2. External CSS file.
.
3. Internal < head > style.
.
4. Inline style.
Example:
body
{
background-color: #00CCFF;
}
h1
{
color: #0000FF;
}
p
{
font-family: Arial, Helvetica, sans-serif;
}
Internal styles:
The internal style will be applied only to the document that declares it.
Example:
Inline styles:
The inline style is only applied to the HTML element that declares it.
Example:
Example:
p
{
font-size: 9px;
font-style: normal;
font-variant: small-caps;
}
p
{
font-size: 10px;
font-style: italic;
}
This is because the internal style has higher priority than the external style sheet.
p
{
font-size: 12px;
font-style: italic;
font-variant: small-caps;
}
This is because the inline style overrides any other used styles.
Background color
Example:
body
{
background-color: #FF0000;
}
Background image
Example:
body
{
background-image: url(bg_image.jpg);
}
The value of this property defines how the repeat will occur, the value can be one of the following:
• repeat : The image is repeated both horizontally and vertically.
• repeat-x : The image is repeated only horizontally.
• repeat-y : The image is repeated only vertically.
• no-repeat : The image is not repeated.
Example:
body
{
background-image: url(bg_image.jpg);
background-repeat: repeat-y;
}
Background position
To set the background position of a background image, use the “background-position” property.
The horizontal position is specified first, and then the vertical position, If only one value is used, it sets the
horizontal position only and the vertical position will be center by default.
Example:
This will use “bg_image.jpg” as a background image, place its upper-right corner in the upper-right corner
of the body, and repeat it vertically.
Background attachment
To set if a background image is to be fixed or to scroll with the page use the “background-attachment”
property.
Example:
body
{
background-image: url(bg_image.jpg);
background-attachment: scroll;
}
This will make the background image scrolls with the rest of the page.
Using the shortcut
You can set all background properties in one declaration using the shortcut property “background”, the
values have to be in the following order:
background-color, then background-image, then background-repeat, then background-attachment, and
finally background-position.
Example:
body
{
background: #00FF00 url(bg_image.jpg) repeat-y fixed 100% 0;
}
This sets the background color to green, uses the image “bg_image.jpg “ as a background, repeats it
vertically, and places its top right corner at the top right corner of the page.
Text color
Example:
This sets the HTML element < p > and the HTML element < h1 > to red.
To set the background color of an element, use the property “background-color”, this property was
explained in CSS background lesson.
Text direction
To set the text direction, use the “direction” property, it can take one of two values:
• ltr: sets the direction to be from left to right as in English and French.
• rtl: sets the direction to be from right to left as in Arabic and Hebrew.
Example:
body
{
direction: rtl;
}
This sets the text direction of the whole document to be from right to left.
Text align
to align the text contained in an element to the element, use the property “text-align”, this property can
take one of the following values:
left, right, center, or justify.
Example:
P
{
text-align: right;
}
This aligns the element < p > text to the right of the element that it’s contained in.
Text indent
To indent the first line of a text, use the “text-indent” property, the value can be an absolute length, or a
percentage value.
Example:
P
{
This indents the first line of the HTML element < p > 15 pixels.
Text transform
To set the text letters case, use the property “text-transform”, this property can have one of the following
values:
• none: no transformation.
• capitalize: the first letter of each word will be in upper case.
• uppercase: all letters will be uppercase.
• lowercase: all letters will be lowercase.
Example:
P
{
text-transform: lowercase;
}
This sets all the < p > element text characters to be in lowercase.
Text decoration
To set the text decoration, use the property “text-decoration”, it can have one of the following values:
• none: no decoration
• underline: the text will be decorated using a line under it.
• overline: the text will be decorated using a line over it.
• line-through: the text will be decorated using a line through it.
Example:
.underline
{
text-decoration: underline;
}
This causes any text element that uses this class to be underlined.
Letter spacing
To increase or decrease the space between characters, use the property “letter-spacing”, it can have one
of the following values:
Example:
This sets the space between all characters in the document to 1 pixel.
Word spacing
To increase or decrease the space between words, use the property “word-spacing”, it can have one of the
following two values:
Example:
P
{
word-spacing: 2px;
}
This sets the space between all words in the document to 2 pixels.
Font family
To set the font for a specific text, use the property “font-family”, the value can be more than one family
separated with a comma, the browser will display the text using the first font, if it’s not supported by the
operating system, it will use the next font, if no font is supported, it will use the default font.
Example:
body
{
font: Arial, Helvetica, sans-serif;
}
This sets the HTML document font to one of the specified fonts starting from left, if no font is supported,
then the browser default font is used.
Font size
To set the font size, use the property “font-size”, the value can be one of the following values:
xx-small, x-small, small, medium, large, x-large, xx-large, smaller, or larger
It can be also a length value or a percentage.
Example:
Body
{
This sets the font size of the whole HTML document to 12 pixels.
Font weight
To set the weight of a font, use the property “font-weight”, the value can be one of the following values:
normal, bold, bolder, lighter, 100, 200, 300, 400, 500, 600, 700, 800, or 900
Example:
.strong
{
font-weight: bold;
}
This sets all the text of the elements that use this class to be bold.
Font style
To set the style of a font, use the property “font-style”, the value can be one of the following values:
normal, italic, or oblique.
Example:
.italic
{
font-style: italic;
}
This sets all the text of the elements that use this class to be italic.
Font variant
To set the variant of a font, use the property “font-variant”, the value can be one of the following values:
normal or small-caps.
Example:
.caps
{
font-variant: small-caps;
}
This sets all the text of the elements that use this class to be uppercase.
Borders in CSS are not just the table borders as in HTML, with CSS any HTML element can have borders,
CSS adds many effects to be applied to these borders.
To set the width of a border, use the property “border-width”, the value of this property can be one of the
following values:
thin, medium, thick, or an absolute value as the table “border” attribute in HTML.
Example:
table
{
border-width: 2px;
}
This sets the width of the border of the < table > element to be 2 pixels.
Border style
To set the style of a border, use the property “border-style”, the value of this property can be one of the
following values:
none, dashed, dotted, double, groove, hidden, inset, outset, ridge, or solid.
Example:
Table
{
border-width: 1px;
border-style: dotted;
}
This sets the border style of the < table > element to be dotted, and its width to 1 pixel.
Border color
To set the color of a border, use the property “border-color”, the value of this property can be any HTML
color.
Example:
table
{
border-width: 1px;
border-style: dotted;
border-color: blue;
}
This sets the style of the border of the < table > element to dotted, width to 1 pixel, and color to blue.
Note: All the previous properties can take up to 4 values, in the previous example if color is defined as:
The top and bottom borders will be colored as blue and the right and left borders will be colored as green.
The top border will be colored as blue, the right border will be colored as green, the bottom border will be
colored as red, and the left border will be colored as yellow.
You can set all the properties in one declaration, to do so use the property “border”, and the order is:
border-width, then border-style, and finally border-color.
Example:
Table
{
border: 1px dotted blue;
}
This sets the border width of the < table > element to 1 pixel, the style to dotted, and the color to blue.
There are other border properties to set the border values for only one of the borders, they have the same
values, they are:
The only difference between these properties and the previously explained properties is that they can’t
take more than one value to be set for that single border.
The margin is the space around the element from the four sides, the margin attributes enables you to
increase or decrease this space; the space can be a negative value, which may make elements overlap.
Using margins is very easy and straight forward, to declare the margin you can use the following
properties:
Example:
.margins
{
margin-top: 5px;
margin-right:10px;
margin-bottom: 5px;
margin-left: 12px;
}
This will set the top margin of any HTML element that uses this class to 5 pixels, the right margin to 10
pixels, the bottom margin to 5 pixels, and the left margin to 12 pixels.
A shortcut property can be used to set all the margins in one declaration; the property is “margin”, and
the order is:
Example:
.margins
{
margin: 5px 10px 5px 12px;
}
You can use from 1 to 4 values for the “margin” property, and the browser will assign a value for each side
the same way as in borders.
The padding is the space between the element border and the element content from the four sides, the
padding attributes enables you to increase or decrease this space; unlike spacing padding space values
can’t be negative.
Example:
table
{
padding-top: 5px;
padding -right:3px;
padding -bottom: 5px;
This sets the top padding of the < table > element to 5 pixels, the right padding to 3 pixels, the bottom
padding to 5 pixels, and the left padding to 2 pixels.
A shortcut property can be used to set all sides padding in one declaration; the property is “padding”, and
the order is:
Example:
table
{
margin: 5px 3px 5px 2px;
}
You can use from one to four values for the “padding” property, and how the browser will assign a value
for each side works the same as in borders and margins.
To set the list style marker type, use the property “list-style-type”, this property can have on of the
following values:
none, circle, disc, square, decimal, decimal-leading-zero, lower-alpha, upper-alpha, lower-greek, lower-
latin, upper-latin, lower-roman, upper-roman, armenian, cjk-ideographic, georgian, hebrew, hiragana,
hiragana-iroha, katakana, or katakana-iroha.
Example:
Fruits:
• Apples
• Bananas
To set the position of the list item marker, use the property “list-style-position”, the value that can be
assigned to this property may be on of the following:
inside or outside.
Example:
Fruits:
• Apples
• Bananas
To use a custom image as a list style marker, use this property “list-style-image”, the value of this
property is a URL.
Example:
This sets the image “list_image.jpg” as the marker for this list style.
A shortcut property can be used to set all the properties of the list style in one declaration, the property is
“list-style”, and the order is:
Example:
ul
{
list-style: disc inside url(“list_image.jpg”)
}
This sets the marker style to disk, the position to be inside, and overrides the marker to be the mage
“list_image.jpg” instead of disc.
The dimension properties enable you to increase or decrease the height and width of HTML elements.
Line height
To set the distance between the lines of an element, use the property “line-height”, the value of this
attribute can be an absolute value or a percentage.
Example:
p
{
line-height: 0.3cm;
}
Width:
To control the width of an element, you can use three properties, they are:
Example:
table
{
width: 100%
}
The display properties enable you to set the way to display elements and the position of the element
relative to another element or to the whole document.
Float
To set the appearance of an element or an image relative to another element, use the property “float”, this
property can have on of the following values:
img
{
float: left;
}
Position
To set the position of an element, use the property “position”, this property can have on of the following
values:
Example:
h3
{
position: relative;
right: 10px;
}
This will position the < h3 > tag at 10 pixels to the right relative to its original position.
The “position” property just defines the position and it needs one of the following properties:
Visibility
To set if an element will be visible or invisible, use the property “visibility”, it van have one of the following
values:
visible or hidden.
Example:
.hide
{
visibility: hidden;
}
This will make the element that uses this class to be invisible when the document is rendered.
Cursor
To set the type of the cursor, use the property “cursor”, this property can have one of the following values:
crosshair, help, move, pointer, text, url, wait, e-resize, ne-resize, nw-resize, n-resize, se-resize, sw-resize,
s-resize, or w-resize.
Example:
Vertical align
To set the vertical alignment of an element, use the property “vertical-align”, this property can have one of
the following values:
sub, super, top, bottom, middle, text-top, text-bottom, an absolute value, or a percentage.
Example:
td
{
vertical-align: top;
}
z-index
If there are elements that overlap, and you want to display them as layers, you can define the order of the
element using the property “z-index”, the value is a number that represents the element order.
Example:
img
{
z-index: -1;
}
This will place the < img > element behind all other elements.
Link
To define link properties, you can use four pseudo classes, they are:
Example:
a:link
{
color: #0000FF;
}
a:visited
{
color: #FF0000;
}
a:hover
{
color: #00FF00;
}
a:active
{
color: #0000FF;
}
This sets the link color to be in blue when unvisited and when active, to be in red when visited, and to be
in green when mouse goes over it.
First letter
To set a different style for the first letter of an element, use the pseudo class “first-letter”, this can set the
first letter font, color, and text properties.
Example:
p
{
font-size: 10px;
}
p: first-letter
{
color: red;
}
This will display the first letter of the element < p > in red color.
First line
To set a different style for the first line of an element, use the pseudo class “first-line”, this can set the
first line font, color, and text properties.
Example:
p
{
font-size: 10px;
}
p: first-line
{
color: red;
}
CSS adds support for different media types, you can create many styles, and each style defines how the
document will be styled when its media type is used.
There are two ways to use a different CSS for different media types in the same document, you can place
the style internally in the HTML document, or you can create as many CSS files and link them to the HTML
document.
To use internal media CSS, use the “@media” rule, the rule(s) will be inside the < style > elements.
Example:
@media screen
{
p
{
font-size: 12px;
}
}
@media print
{
p
{
font-size: 10px;
}
}
This will set the size of the text of the < p > element to 12 pixels when displayed at the screen, and to 10
pixels when printed.
To use external CSS files, add a < link > element inside the < head > element of the HTML document for
every CSS file to be used, add the attribute “media” to the element, and specify the media type that will
use this file, media values can be one of the following:
all, aural, braille, embossed, handheld, print, projection, screen, tty, or tv.
Example:
We have two CSS files, the first one is named “screen_style.css”, and it defines how the HTML document
will be displayed on screen, the second one is named “print_style.css”, and it defines how the HTML
document will be displayed when printed, to use both of them in the HTML document:
Printing HTML documents always causes problems, with CSS you can specify a printing style and attach it
to the document.
CSS has a great support to document printing, it adds many rules that helps in adjusting the printing
measures of the document.
Percentage
Values
The absolute values represent a measurement, there are many measurements in CSS, so the
measurement unit has to be stated.
• cm: centimeter.
• em: font size.
• ex: half of the font size.
• in: inch.
• mm: millimeter.
• pc: pica.
• pt: point.
• px: pixel.
Colors
Layout
Classification
Positioning
Bottom Sets the bottom position of the element in relation to the bottom
of the next positioned element in the document.
Height Sets the height of the object.
Left Sets the position of the element relative to the left edge of the
next positioned element in the document.
Overflow Sets how to manage the content of the element when the
content exceeds the height and/or width of the object.
Position Retrieves the type of positioning used for the object.
Right Sets the position of the element relative to the right edge of the
next positioned element in the document.
top Sets the position of the element relative to the top edge of the
next positioned element in the document.
Visibility Sets whether the content of the element is displayed.
Width Sets the width of the object.
Pseudo-classes
active Sets the style of anchor when the link is engaged or active.
cursor Sets the type of cursor to display as the mouse pointer moves
over the element
hover Sets the style of the anchor when the user hovers the mouse
over the links.
link Sets or retrieves the style of the < a > element for the default
state of the link.
visited Sets the style of the anchor for previously visited links.
I opted not to style the list ul or il elements themselves, but rather encase the list in a DIV so that we’ll
be able to address the different elements within it in a simple manner. This isn’t really necessary—you can
often achieve exactly what you need by styling the ul element and addressing the elements under it,
instead. Remember though, that the element that you wrap the list around needs to be a DIV, rather
than a SPAN, since strict XHTML won’t validate an Inline element having a Block child (you could, of
course, add display: block; to its class, by why go that far when DIV is ready and waiting to serve?).
Since I’m going to be referring to elements of the Box Model frequentry throughout this document, you
may want to check out the Box Model article to get better acquainted with how CSS tells the browser to
draw elements onto the display device.
We’ll start by taking the reigns and assigning values to several well-known properties:
The first thing we do is eliminate the padding and margin to the left of the text. We may want to recover
that later, but for now we’re simplifying the list. We also remove the bulletpoints completely by assigning
none to the list-style-type property. Lastly, we assign font and line-height properties. You may be
wondering why bother with line-height? This is a technicality that you’ll be able to experiment with later
—If you just set a font size, sometimes the listil items will distance themselves from each other in
Internet Explorer, creating what looks like a margin, even if you specify the li’s margin property to 0.
There is a similar problem with horizonal lists, however the solution to that problem is different. The
problem often shows itself when the line-height is too small compared to the font size, though your
best bet is to simply check your design in Internet Explorer and see how it renders. Also keep in mind that
while the UL element is a Block element, the LI element is of type list-item, which means that the line-
height property governs its height, rather than the height property. In fact, if you were to replace the line-
height property with the height property of the same value, you’ll get some amusing results, which will
vary from one browser to another.
Now that we have links on our list, we should style them as well:
.list_container a { display: block; padding: 1px; padding-left: 10px; width: 200px; background-color:
#FFF; border-bottom: 1px solid #DDF; } .list_container a:link, .list_container a:visited { color: #369;
text-decoration: none; } .list_container a:hover { background-color: #369; color: #fff; }
Notice that the only elements that were specified a width were the a elements. In other words, at the very
least, the encasing DIV is taking up all the horizontal space that it can. Normally, when encasing a list
with a DIV, you would need to specify a width for the a elements, and for the DIV itself. You can’t leave
the width of the a elements empty, or the il elements will react badly in different manners depending on
the browser. You also shouldn’t set the a width to 100%, since this will conjure its own set of problems,
even if you’ve set the DIV’s width to a specific amount of pixels. This may seem troublesome, but there’s
really nothing preventing you from setting both width properties to the same pixel value, which is the
recommended route.
Let’s not write off the list markers just yet. Remember that it’s always nice to get more graphical value out
of less code, when possible (and when appropriate!). We’ll make three changes to the CSS:
We’ve covered some basic uses of HTML lists as navigational elements. You can see this is no rocket
science, and is very easy to manipulate and scale. In CSS Lists: Part 2, we’ll get into more complex lists,
and more subtle property usage.
We’ll start with a version that intentionally seeks to maximize the graphical detail that we can attain, by
styling every element in the HTML. This is also where we’ll encounter the first CSS-standards browser
issue:
.list_container li { width: 200px; border: 1px solid #000; margin-bottom: 4px; } .list_container a
{ display: block; padding: 2px; padding-left: 10px; background-color: #A74B4B; border: 2px solid;
border-color: #C98787 #6C3131 #6C3131 #C98787; } .list_container a:link, .list_container a:visited
{ color: #FFF; text-decoration: none; } .list_container a:hover { border: 2px solid; border-color:
#6C3131 #C98787 #C98787 #6C3131; }
We left the UL element unchanged, since it mainly styled font properties which will stay the way they are
for now. Something may draw curious attention in the code above: The width property was moved from
the a element to the LI element—I’ll explain this in a moment. The LI element was also added a 1px
black border, and a margin of 4px in order to space the list items out. The main graphic element that was
added was the button-like border to the a element. I used the short-hand definition of border-color,
defining the four colors clock-wise. Here’s what we got:
• List Item 1
• List Item 2
• List Item 3
Considering how little HTML code makes up this list, this is quite remarkable. If you tried doing that using
tables, you’d probably have to use about 10 times the code. Now, why was the width property moved
from the a element to the LI? Didn’t I write in CSS Lists: Part 1 that you’re supposed to keep the width
property to the a element and the DIV? I did, and for good reason: this specific list will function one way
in Explorer 6, and another in Firefox and Explorer 7. This is because Explorer 6 does not implement CSS to
exact standards. Let’s first go over how the CSS standard browser “sees” things: Think about it like boxes
within boxes. If you define the inner box to a certain size, you dictate the outer box to at least that size.
Remember that since the a elements have the property of display: block, that they will take up
however much horizontal space that they can. Now consider that the a element is the one which dictates
the width, and the LI elements wrap around it—that would mean that the LI elements would have to take
into consideration all of the a element’s margins and borders, something that not all browsers do well.
Instead, we define the LI element’s width, and let the a element “flow” within it, taking up however much
space it needs, like pouring liquid into a specific-size container. This is easier for the browser to calculate
and render. This, again, has to do with the Box Model, as was mentioned in the previous article.
Internet Explorer 6 doesn’t support CSS standards fully, and renders things differently: Even though the
a’s property of display was set to block, the link’s active area will only react when the cursor touches the
text itself, not the entire list item. In fact, the oddity goes further—if you’ve assigned border reactions to
the a:hover (and we did), they will indeed take effect, but only if you trigger them by moving the cursor
over the link text itself.
Quite a few of you reading this are probably thinking to yourselves: “if this is some experimental future-
standards thing that isn’t applicable today, why didn’t you say so earlier?”... Well, because it isn’t. The the
above “mix” of properties is already implemented on many sites, for 3 main reasons:
• Even though it does not render exactly the same on the two latest versions of Explorer, both
versions render it acceptably. Even if you have no conditioning for alternate CSS when a different
A few things to note: When assigning specific margin values, or specific border values, make sure you
have a constant sum of values for the top/bottom, and for the left/right. If you don’t, the overall object
will actually change size. So why does the a element start with a margin-right of 24px? Because of the
potential margin plus the potential border. It starts off with just a 1px uniform border, so the object
moved 1 pixel to the right (because it is left-aligned). If you were to move your cursor over it, it would
increase its border-left to 15px, and its margin-left to 10px, a total of 25. So again, why 24 instead of
25? Because of the initial 1 pixel border—it’s counted in as part of the left/right sum. When the link is in
hover state, the margin-right is reduced to 0.
And now for something completely different:
• List Item 1
• List Item 2
• List Item 3
Images were expected at some point, weren’t they? This is the exact same HTML as the rest of the lists,
the only thing that’s changed is the use of images. In fact, this is a mild implementation of them—you can
achieve all sorts of effects using filters. Also there’s no position change, which, when using images, can be
used to create effects like pushing buttons or flipping switches. Here’s the CSS:
In future documents, I’ll expand on how additional HTML elements can be styled within lists while
maintaining the same course of containing the entire navigational area within one selector class.
I’ll give examples of horizontal lists, which are very useful, and have a special affinity for
background images and buffers due to their fixed height (you can guess where I’m going with
this, since the line-height doesn’t change...).
That was a plain list. No properties were assigned to it. Now I’ll add the following CSS:
.horiz li { display: inline; }
As was done in previous installments of CSS Lists, I’m wrapping the list with a DIV element, and styling it
and its descendant elements. The HTML/XHTML I’m working with is:
The next thing to do is to remove the “vestigial” inherent list properties, which means removing the
margin, padding, and list-style-type property values (by ‘removing’ I of course mean either resetting to 0
or none). While I’m doing that, I might as well set the font-family, font-size, and line-height property
values:
.horiz ul { margin: 0; padding: 0; list-style-type: none; font-family: Georgia, “Times New Roman”, Times,
serif; font-size: 14px; line-height: 17px; }
The list now looks like one stack of inline elements, which, in a way, it is:
• List Item 1
• List Item 2
• List Item 3
If you remember the sequence of steps from CSS Lists: Part 1, you know that I’ll now start messing
around with the A elements. However, one of the big differences between the lists I’ve demonstrated so
far, and horizontal lists, is that horizontal lists don’t have the same link width for each link. While this is a
mixed blessing, it’s more of an advantage than a disadvantage, since you waste less space on your page
overall.
What’s unexpected, was that there would be any space between the list elements. Remember though, that
they’re inline elements now, which means that they’ll act like ones, and treat white spaces, which include
newlines, as, well, spaces... This requires a tweak to the markup:
<div class=”horiz”> <ul> <li><a href=”#”>List Item 1</a></li ><li><a href=”#”>List Item 2</a></li
><li><a href=”#”>List Item 3</a></li> </ul> </div>
If you’ve been around since the olden days of image stacking, you’ll recognize this trick as “tag breaks” or
“in-tag newlines”. There was a need to remove the newlines between the LI tags, so the first thing you
would think of doing is just placing them all in a row. This works, but makes for extremely un-
maintainable markup, especially when you have 8 list items and 8 corresponding link URLs. However,
neither HTML, nor XHTML, mind if there’s a newline within a tag. This lets us close the ending LI tags the
line after they open.
If you do want spaces between the list items, you’d usualy use the margin property instead of white-
spaces. We’re not barbarians, you know...
As well, I didn’t find the room to comment about the usage of the padding property in the A element style
rule until now. It’s the usual ‘top-clockwise’ shorthand syntax, but unlike vertical arrays, I had to pad all
sides. This is because, just like the LI elements, the A elements are also inline, which means that they’ll
take not a pixel more than they need to render (unlike block-level elements, which will take whatever
horizontal space you give them). This meant that I needed to pad their right side by the same amount as I
Nothing new here. I just gave the :hover state a slightly brighter color. I also added some borders to the
links for spice. Here’s how the list looks now:
• List Item 1
• List Item 2
• Very Long Link
• Short
Before I move on, I should mention this little neat feature: you can center the list by centering the text of
the UL element. That is to say, by adding this:
.horiz ul { text-align:center; }
Why would that happen? Well, now that every element that’s a descendant of the UL element is inline, it’ll
be effected by the text-align property. And remember that this rule selects the UL element, not the DIV,
so you can still throw things in there and have them unaffected by the centering.
If you consider the usage of horizontal links, they’re often used to guide the visitor around the broad
sections on the site. They also sometimes act as guides to where the visitor currently is. Look at the
following style rule:
.arbitrary { border-width: 5px 3px 5px 3px; border-style: solid; border-color: #bc787a; }
This can be a means of tagging the page the visitor is currently visiting. You’re styling one specific LI
element and adding, in this case, border properties to it. Note how much larger the top, and the bottom
borders had to be made, however. This, again, relates to all of these elements being inline. The A
elements, even though they were given border and padding to, one would think, ‘inflate’ the LI elements
that wrap them, they did so only horizontally, not vertically. Thus, in order to see the vertical border
applied to the LI elements, they have to surpass the A’s element box. Once you’ve done that though,
you’re in the clear, this will render properly in Firefox, Internet Explorer versions 7 and 6, and Opera.
The subject of images in lists will likely be covered in the next installment. You’d be surprized in what
ways lists can manipulate images, and do so with relatively few properties at that.
But First!
A prerequisite to properly implementing selectors is understanding the Document Tree. If you haven’t
already, it’s recommended you go over the Document Tree article which details how the document tree is
applied to HTML/XHTML documents.
The Type Selector is the easiest to understand, and easiest to implement selector. It applies a CSS Style
Rule to an HTML/XHTML element. For example:
body { margin: 0; padding: 0; background-color: #FFF; }
The above Style Rule applies solely to “elements” of type BODY. Incidentally, there’s only one. This is a
common way to rid the page of its variable, and browser-dependant margins (and in some browsers,
padding), and to set the background color while you’re at it. Let’s look at another type selector
implementation:
p { font-size: 0.9em; text-indent: 0.5em; padding: 2px; }
This is a common styling of a paragraph (the P element). The font-size has been set to 0.9em (or 90%)
of the parent element, a padding of 2px has been added, and a text-indent of 0.5em has been added,
which will only effect the first line of text within the block. Do you see the advantage of composing a style
rule this way? It makes no assumptions at to the font-family, or to the absolute font-size of the parent
element. It doesn’t care what the color scheme is. It applies its rules of styling to what’s relevant to it,
and it alone. This, again, touches on the subject of Selector Structuring, but why not sneak in some extra
information here an there if I can (call it standards propaganda...). Of course, this, by itself, isn’t very
useful, since it will target every single P element on the page, which is a bit unrestrained. We’ll need to
get to Descendant Selectors and Classes before we can properly select just what we want, within the
contained areas we want it.
Something which should be covered early on is multiple selection. This allows you to place multiple
selectors before a single style rule, simply be dividing them by commas:
h1, h2, h3, h4 { color: #444; }
This does exactly what you’d expect it to do. It applies color: #444; to all H1, H2, H3, and H4
elements in the document.
Universal Selector
When used by itself, the Universal Selector only appears in one way (usually, when it’s a document that’s
intended for the web), and is rather limited in use:
Descendant Selectors
With Descendant Selectors you’re getting more specific about which elements you’re going to style.
Descendant Selectors can actually refer to Types, Universals, IDs, Classes, and Attribute Selectors, it just
means that you’re selecting by addressing the elements you want using their parents to guide the Style
Rule to its targets. Visually, this is easier to understand. We’ll start with some HTML code:
<div> <h3>Post Title</h3> <em>Post Date</em> <p>Post Contents <i>Author</i></p> </div>
Now we’ll use Descendant Selectors to select the element types, and then their descendants, which we
want to style:
div h3 { text-decoration: underline; } div i { color: #0000CC; }
Both the H3 element and the I element were descendants of the DIV element, and so each respective
Style Rule was applied to each element. This is getting more specific, but it’s still somewhat broad. You’ll
still need Classes and IDs to properly target (select) just the elements you want and not catch something
else in the document that happened to have the same relationship structure.
Class Selectors
The Class Selectors are the most often-used, and over-used type of selector. They’re usually the first
selector that people who are learning CSS are introduced to, and thus it becomes the one they rely on the
most. This is not without reason, however. You’re telling the renderer of the document to specifically select
an element with a specific name. No ambiguity whatsoever. However, as the person who’s designing both
the style and the structure, you can make sure that there’s no ambiguity by combining Class (and ID)
Selectors with Type and Descendant Selectors, and creating both less Markup and less Style Rules (once
again, this has to do with Selector Structuring, which will be properly covered in a separate article).
This time, I’ve added a class attribute to the DIV element. Now, by combining several types of selectors, I
can achieve different goals:
.posting { font-family:Georgia, “Times New Roman”, Times, serif; } .posting h3 { text-decoration:
underline; margin: 0; } .posting p { margin: 0.4em; } .posting em { font-size: 0.8em; } .posting p i
{ display:block; color: #0000CC; }
Ok, so that might have been a bit too many Style Rules for one code block, but the big picture is
important in this case. The first rule sets the font-family of the posting class. Remember that the font-
family property is inherited, so I don’t have to worry about the rest of the elements within the DIV
element which I’ve styled with the posting class.
The next rule is a Class/Descendant rule. I’m selecting an element type which is a descendant of any
element that was styled using that specific class. In this case, I’m selecting any H3 element which is a
descendant of any element which was styled by the posting class. Any element matching this description
will be assigned a text-decoration property, and a margin property.
The third and fourth rules are just like the second. This time, they’re selecting P and EM elements, and
assigning them margin, and font-size properties, respectively.
The last rule is technically the same as the previous three rules, except I’m being very specific about
which element I want to style. I’m looking for an I element, which is a descendant of a P element, which
is a descendant of any element which was styled by the posting class. In many programming languages
this would be considered object-orientation, but here it’s more like navigating the Document Tree. You’re
basically zooming-in on your target, and making sure that nothing else gets “accidentally styled” along the
way. If there was an I element within the DIV element, but not within the P element, it would not have
been effected.
Another thing to mention about Class Selectors, is that a single element can be styled using more than
one class. It’s easier than it sounds:
.greenish { color:#009966; } .biggie { font-size: 1.2em; font-weight: bold; } <span class=”greenish
biggie”>Some Text</span>
This normally finds its uses in very large style sheets, with dozens of rules, where you have many
overlapping qualities and you can narrow things down by assigning more than one class to a single
element. This also finds use in style-sheet-switching, where you’d like to switch a color scheme, for
example. You have one .css file that sets everything but the colors for your pages. Then you have another
one that “houses” the color scheme. In that file, you don’t name color classes like “Maroon” or “Hazel”—
instead, you assign names for the various elements that will be colored by the different hues of the color
ID Selectors
ID Selectors are similar to the Class Selectors in how they operate, except that they look for the common
HTML/XHTML ID attribute. This attribute is used for other things, unlike the class attribute which is
designed for CSS use. Forms use IDs to identify value containers, and JavaScript uses them as direct
handles to elements on the document. Also, there can only be one ID of each name assigned to one
element within a document. This is simply the nature of the web standards, and isn’t CSS-specific. Using
IDs to style elements has several advantages: First, if you’re using JavaScript on elements you’re going to
style, then you’re already using IDs, so why identify an element twice? Second, if you really only have one
“thing” (that’s a technical term) of its kind on a page (let’s say, a right column), this will make sure you
don’t assign the same handle/identification to more than one element on the document.
It’s the same as Class Selectors, except with a # instead of a .. You can also use descendant selection
just like the class/type selection example above. It should be noted that IDs are commonly reserved by
designers for DIV elements and SPAN elements, although this isn’t written in stone, it’s just what you’ll
usually find when you’re looking over the source of pages with interesting CSS implementations (which, by
the way, is a highly recommended method of education).
Half-Time
That’s it for CSS Selectors Part 1. In Part 2 we’ll get into the cool pseudo-classes (a:hover!), and the
more gritty Selector Types, which aren’t really gritty, they’re simply not supported properly by enough
browsers.
Unit: Pixels
Pixels define an element’s size using a specific humber of pixels. This is very convenient when designing
for digital displays, since it gives you exact control over the size of the element, allowing you to make
exact calculations of width and height for your design. However, there are several downsides to using
pixels you should be aware of: First, setting a font’s size using pixel units does not allow the user to resize
that font using their browser settings. When you set a font’s size to 12 pixels, it will always have a height
of 12 pixels, regardless of what the user has set the default font size in their browser to. This is an
accessibility issue that, if you choose to use pixels to set your font sizes with, should be dealt with using
other means (for example, allowing the user to choose from two or more different style sheets). Secondly,
when it comes to print media, pixels have no real value. If you design a document for print, it’s up to the
Unit: Ems
Ems are a relative measurement unit. One ‘Em’(1em) is equal to the height of the capital letter “M” in the
default font size. When applied in CSS, the Em represents either the user’s default font size, or the size of
the parent element’s font size, if one is available. When using Ems for sizing fonts, the fonts will resize
according to the browser’s default font size setting. That is, if the upper-most definition of the font size is
defined by Ems (or any other relativee unit of measurement), and every successive unit set in every
descendent element is also defined using a relative unit, then the text on the entire page will be user-
resizeable. If the parent of the element using Ems to size its fonts defines its own font size using absolute
units (such as Pixels or Points), then the font of that element will ‘snap’ to that parent’s font’s size,
instead. This means that setting descending element font sizes to Ems does not mean they will be user-
resizeable if their parent element’s font isn’t resizeable. Ems are set to decimal units, like 1em, 0.9em,
and 1.1em. These units can be thought of as percentages of the parent element, where the top-most
level is set to the browse default font size. For example, if the browser’s font size is set to ‘Normal’, then
setting the font-size of the BODY element to 1.1em will mean that the font size inside the BODY
element will be 110% the size of the browser’s ‘Normal’ font size. If the user then set their browser’s font
setting to ‘Large’, then the font size inside the BODY element will be 110% the size of the browser’s
‘Large’ font size. Now suppose that the BODY element’s font-size was set to 10px, and the P element’s
font-size was set to 0.9em. This means that any text within P elements will be 9px, regardless of what
the user set their browser’s font setting to.
Here are some examples of Ems in action. First, look at the following code:
<style type=”text/css”> <!-- .parent_elem { font-size: 28px; font-family: “Times New Roman”, Times,
serif; } .parent_elem p { font-size: 0.7em; line-height: 1.5em; width: 12em; background-color:#FFCC00;
} --> </style> <div class=”parent_elem”> The letter ‘M’. <p>Text within the P element.</p> </div>
As you can see, the entire P element has been resized. It was scaled down to fit the newly assigned font-
size value of 24px to the parent_elem class. By mixing Ems and Percentage values you can create a
completely scaling design, that is either defined by you, or the user’s browser settings. Remember though,
that if you want the user to be able to scale the fonts themselves, you have to allow them to control the
Unit: Exes
Exes are similar to Ems, in that they are a relative unit of measurement that defines 1 unit to be equal to
the size of the letter “x” in the default font size. Most other properties that apply to the Em unit of
measurement apply to the Ex unit of measurement. However, most browsers do not support this unit of
measurement properly, and it is not recommended for use in documents intended for browsers.
Unit: Percentages
When assigning percentage units (%) to a property that isn’t font-size or line-height, that value always
relates to the parent block of that element. When assigning percentage units to the font-size or line-height
properties, they act like the Em unit, where 100% equals 1em. If you set the font-size property of an
element to 100%, and that element’s parent block is the BODY element, the result will be the same as
setting the font-size to 1em—namely, the size of the text will become the browser’s default font size. It’s
important to remember that percentage values mean different actual absolute values when assigned to
the font-size and line-height properties, and when assigned to everything else. Assigning 100% to the
width property of an element is completely different than assigning 1em to it, for example.
Here’s an example of Ems and Percentage values mixed within the same elements:
<style type=”text/css”> <!-- .parent_elem { font-size: 18px; font-family: “Times New Roman”, Times,
serif; } .parent_elem p { font-size: 120%; line-height: 150%; width: 80%; background-color:#FFCC00; }
.child_elem { font-size: 0.7em; line-height: 1em; } --> </style> <div class=”parent_elem”> The letter
‘M’.<br /> <span class=”child_elem”> Text within a SPAN set to the child_elem class. </span> <p> Text
within the P element.<br /> <span class=”child_elem”> Text within the P element, within a SPAN set to
the child_elem class. </span> </p> </div>
Note how the percentage values have a different effect when assigned to the width property, and when
Decisions...
It will be up to you to decide which units to assign to which properties, and to take into consideration
accessibility, media type, different display resolutions, and compatibility, among other things. As a general
rule, if you don’t assign relative-only values to all of your fonts, you should provide a means to change the
style sheet for your pages, so that the font size may be changed by the user. Also remember that when
designing a page that will fit the entire browser window, to mind each element’s size in terms of whether
it’s relative or not, since stretchable designs can ‘break’ in certain resolutions if their elements weren’t
matched properly along the way.
Floating Elements
A commonly misunderstood, and highly underrated property of CSS is the float property. The ability to
float elements has been around since earlier in HTML’s life, but has been cemented in CSS in terms of
rules of implementation, even if not all browsers implement floated elements properly when they’re
presented with an overly complicated scenario.
The broad definition of “float-ing” an element is that you assign that element a certain amount of the
horizontal space (width) within its containing block, and tell it to allow other content to flow down the right
or left edge of it, instead of it taking up all of the horizontal space that it would usually take up. The most
common example is the IMG element: If you were to place text within a document, followed by a BR,
followed by an image, followed by another BR, and then followed by additional text, the image would take
up however much vertical space it needs, and all of the horizontal space to its right (assuming the
document is left-aligned) will be wasted. If you were “to float” that image to the left, it would allow
content to flow along its right edge, and the browser (or whatever happens to render the document) will
take care of spacing this text for you so that it will align, wrap, and fill the area properly. But this is just
one very common, very simple scenario. The float property allows you to structure many elements around
the document, and is much more powerful that most people give it credit for.
I’ll get browser compatibility out of the way before I delve into the subject, to solve the “should I even be
reading this if it’s not properly suppoorted across every browser ever?” question thing. Floating elements
is an old trick, it’s just being applied to new elements as designers/developers realize that the majority of
browsers support this. It used to apply almost exclusively to images, at least in practice, and you’d see a
mention every now and again that you can float “any block” (followed by sarcastic comments like “Yes!
It’s the World of Tomorrow!”). Today, you really can float any block, and even Internet Explorer 6 will
accomodate most scenarios. If you round up IE6, IE7, Firefox, Opera, and Safari, you get around 99.8%
of the browsers out there (according to current statistics). Even if there’s a shift in browser usage, it’s not
going to be in favor of an older, less compliant browser. Whatever your views are in terms of “who’s
gaining” in the browser wars, it doesn’t matter—all of the latest versions of the aforementioned browsers
have better support for Web Standards and it’s not like one of them is going to start ‘removing support’ as
part of its roadmap.
That said, there are always some creases, since it wouldn’t be fun if things ‘just worked’... However, they
aren’t broad enough for me to round them up in a paragraph, but rather they’re scenatio-specific, which is
why whenever something doesn’t work along the way, in whichever browser, I’ll alert the bells. You’ll
notice, however, that these scenarios are rather specific, easily avoidable, and hardly make floating
elements any less of a powerful tool even if you were to steer clear of them completely.
Two style rules were created: test_properties was given four properties, three of which appear
differently when applied to inline elements than they do when they’re applied to block-level elements
(these would be the background-color, padding, and border properties), and also the width property which
is ignored by inline elements. The second rule, make_it_float, just applies the float property value of
left to an element. Then, there are two paragraphs, one which is styled by just the test_properties
class, and the other which is styled by both. Actually, when I say “paragraph”, I don’t mean the P
element, since that element is inherently a block-level element—I mean SPAN elements with “a
paragraph of text” in them.
Magnesium is the chemical element in the periodic table that has the symbol Mg, the atomic number 12,
and an atomic mass of 24.31.
Magnesium is the chemical element in the periodic table that has the symbol Mg, the atomic number 12,
and an atomic mass of 24.31.
There would have been no difference if the second SPAN element had its display property value set to
block, instead of being applied a float property. The reason for the element becoming a block when being
floated has to do partially with its need to have a set width property (in fact, this is the primary reason).
This, again, isn’t made completely clear in the CSS 2.1 specification, but it is, this time, made clear in
code implementation, rather than browser/renderer implementation. While you can apply a float property
to an element without that element having a set width value, you’ll simply get no consistent results. The
element can have a width value either inherently as part of the element’s definition, like IMG elements,
some elements may have the width HTML/XHTML attribute set, or you can set the CSS width property
value. Any one of these will tell the document renderer that there’s either an absolute width value, or a
relative width value to be calculated, but in both cases there’s a value to work with in terms of absolute
units after all of the calculations are done (units is a generic term here, since pixels are relevant to a
display device, whereas a printing device might use dots or other types of units of measurement).
What else does applying the float property to an element do to the element itself? It aligns it either to the
left, or to the right, within its containing block, depending on the value you’ve set. This isn’t exactly like
aligning elements, since it will react differently to other floating elements, for one thing, but in many
cases, it will, in most respects, have the same effect.
Floating objects will continue to stack until there’s ‘no more width’ to contain them. That is, they’ll keep
trying to appear horizontally, aligning to whichever side they’re floated to, until the containing block can
no longer contain any more of them in its calculated final width. At that point, they’ll go to a new line and
begin again:
Containing Block: a DIV with a border and a set height.
Rules of Engagement
Now let’s talk implementation. You want to float an element, meaning that you want a block of content to
have other element/s to flow to the left, or to the right of it, instead of it monopolizing the entire
horizontal space to its right/left. There are several things that you need to consider in your
implementation.
Floating elements must have a set width. Their width may be set inherently, like in IMG elements, they
could be set by the width HTML/XHTML attribute, or it may be set using the CSS width property—but in
some way, the element that’s being floated must have a width to ‘report’ to the browser/renderer. This is
the way the browser knows how much width to allocate to this element, and how much width is ‘left over’
for the other elements to flow through.
Floating elements allow elements that follow them (elements that come after them in the document) to
flow beside them. They do not effect preceding elements (anything that came before the floating element
within the document). There are actually a few exceptions to this, but they are limited, and I’ll make note
when they’re encountered.
Ducks in a Row
Before delving into a maelstrom of examples, let’s have a look at the plan of attack:
So we have a simple enough set of guidelines:
• The floating element will be ‘aligned’ either to the left or the right edge of the containing block.
• Elements that follow the floating element will ‘measure’ the remaining horizontal space from the
floating element’s available edge to the containing block’s other edge.
The square class makes a 65px wide by 65px high square with background-color, border, margin, and
padding properties out of a SPAN element easily so we can throw them around and experiment. They’re
assigned a display property value of block because they won’t always be floating, sometimes they’ll just
be plain old blocks laying around.
Remember that the idea here is that this floating SPAN (you can use a DIV, it depends on what you
want it to contain) can be an image, it could be holding a paragraph of text, it could contain a list, or a
table, or just about any combination of elements. Obviously, it wouldn’t be this size, but the idea is that
you take a block-level element and float it to achieve a structural goal.
We’ll also define a containing block class so we can more easily see the borders that wrap what we’re
containing:
.containing_block { border: 2px solid #FF9933; padding: 5px; font-size: 12px; line-height: 1.2em; width:
250px; }
Thist is most commonly used when floating an image, but this time we’re floating a generic block, so you
can really replace its contents with anything:
Copper is a chemical element in the periodic table that has the symbol
Cu and atomic number 29. It is a ductile metal with excellent electrical
conductivity, and finds extensive use as an electrical conductor,
thermal conductor, as a building material, and as a component of
various alloys.
If you were to apply the float_right class to the square instead, you’d get the following:
Copper is a chemical element in the periodic table that has the symbol
Cu and atomic number 29. It is a ductile metal with excellent electrical
conductivity, and finds extensive use as an electrical conductor,
thermal conductor, as a building material, and as a component of
various alloys.
Copper is a chemical element in the periodic table that has the symbol
Cu and atomic number 29. It is a ductile metal with excellent electrical
conductivity, and finds extensive use as an electrical conductor,
thermal conductor, as a building material, and as a component of
various alloys.
Tin is a chemical element in the periodic table that has the symbol Sn
(Latin: stannum) and atomic number 50.
Here, the square is nested within not only the P element, but it’s within the text itself. The Marpup for this
is very simple, the square was just moved within the text itself:
<p class=”containing_block”> Copper is a chemical element in the periodic table that has the symbol Cu
and atomic number 29. It is a ductile metal <span class=”square float_left”></span> with excellent
electrical conductivity, and finds extensive use as an electrical conductor, thermal conductor, as a building
material, and as a component of various alloys. <br /><br /> Tin is a chemical element in the periodic
table that has the symbol Sn (Latin: stannum) and atomic number 50. </p>
Now suppose you have something like a list of objects, each with its own icon or thumbnail, and a short
line of text under it. This is a common scenario when you’re designing a control-panel-like design, or
simply a list of thumbnails. Now suppose that you don’t know how wide the area containing these
elements will be, and in fact, that the size of these elements might change (if they’re image thumbnails,
you may want to give the user the ability to change their size).
Now that wasn’t expected... Actually, it was expected, but it wasn’t what we wanted. At this point, it’s
time to introduce float’s partner-in-crime: clear.
Combining float and clear will allow you to create amazing structures with ease, but let’s start with the
basics:
Copper is a chemical element in the periodic table that has the symbol Cu and atomic number 29.
//Stop Floating//
It is a ductile metal with excellent electrical conductivity, and finds extensive use as an electrical
conductor, thermal conductor, as a building material, and as a component of various alloys.
The DIV up there was styled inline, rather than having a class applied to it, which is typical if you only
have just one property you want to apply. Actually, that DIV (without the text in it, of course) is
something you’ll see quite a bit if you go around looking through source markup of pages that float
elements. This is because while you can apply a clear property to any element, it’s very convenient to just
have an empty DIV that ‘clears floating’ from a certain point onward. In other words, you could apply the
clear property to the element that follows the floating element, but you never know what element that will
be, and if you’d need to modify it further because of other properties it may already have.
By placing <div style=”clear:both;”></div> at a location in the document, you know when you
look at it what it’s there for, and it’s easy to maintain later if you want to make modification to your
structure. You have to remember, though, that it’s a DIV, which means that you’re going to want to make
sure you’re within another DIV element to begin with (there’s a simple solution to non-DIVs, I’ll get to it
in a moment).
In the above example, the clearing DIV was placed after the last floating element, after which there’s no
need to worry about the floating effecting any other elements.
But what about when you’re not floating an element within a DIV? A DIV is ‘high up’ in the element
hierarchy, and without going into too much detail about how browsers render pages, we already know we
can’t just throw DIVs within P elements without expecting trouble, even though they’re both block-level
elements. No worries—all we need is an element that’s block-level, and clears both sides, so we’ll make it:
That was the ‘clearing SPAN’. You can place it within P elements, within other block-level SPAN
elements, and within DIVs. So the question is, when to use a clearing SPAN and when to use a clearing
DIV?... Technically, you can use the clearing SPAN anywhere and it should perform just like any of the
two. However, browsers will be browsers, and so there’s a simple rule you may want to follow: If you’re
directly within a DIV, use the clearing DIV. Otherwise, use the clearing SPAN. The reasoning is simple:
If you’re already within anotherDIV—and by this I mean you’re directly under it, not within an element
that is nested within a DIV—you know that placing a DIV won’t disrupt the styling of the parent DIV.
Clearing Above
Clearing will also get you out of some interesting browser incompatibilities. Let’s look at the following
markup:
<p class=”containing_block”> Alpha <span style=”float:right;”>Beta</span> <br /><br /> </p>
Alpha Beta
If you’re using anything but Opera to view this page, then the word ‘Alpha’ appears above the word ‘Beta’.
According to the CSS 2.1 Specification, the two words should appear on the same line. This is subtle, and
in fact technically makes the floating element effect the element above it. According to the specification,
this will only go as far as one box level above the floating element, or any of that elements descendants.
That makes it very subtle, but it’s still valid within the specification, and the Opera Browser implements it
Alpha Beta
If you’re not using Opera, you shouldn’t see any difference. If you view this page using the Opera browser,
the word ‘Alpha’ now appears above the word ‘Beta’, just like it does in other browsers. I should mention:
If you haven’t yet, Opera is free and cross-platform, so there’s no reason not to go and download it for
checking your pages using an additional browser. If you’re designing pages and care about cross-browser
compatibility, then there’s no reason not to have both Firefox and Opera installed on any computer so that
you can check your pages as you’re designing them. Both browsers are a free download, and they both
work on Windows, Mac, and Linux (and BSD, etc.). I’ll even save you the typing: Firefox and Opera.
Bigger Picture
Let’s wrap up by applying float and clear to a mini-document.
We’ll start with the HTML/XHTML:
<div class=”mini_doc”> <h3>Mini Title</h3> <p> ... A whole bunch of text... </p> <br /> <ul>
<li>Copper</li> <li>Tin</li> <li>Zinc</li> <li>Antimony</li> <li>Magnesium</li> </ul> <span
style=”clear:both; display:block;”></span> <span>This is a Footer</span> </div>
Mini Title
Tin is a chemical element in the periodic table that has the symbol Sn (Latin: stannum) and atomic
number 50. This silvery, malleable poor metal that is not easily oxidized in air and resists corrosion, is
found in many alloys and is used to coat other metals to prevent corrosion.
Copper is a chemical element in the periodic table that has the symbol Cu and atomic number 29. It is a
ductile metal with excellent electrical conductivity, and finds extensive use as an electrical conductor,
thermal conductor, as a building material, and as a component of various alloys.
This is a Footer
That was actually one of many ways to create a table-less layout, but that’s another topic altogether. The
main paragraph was given a width and floated to the left, making room on its right for content to flow.
The list found that room to be sufficient and flowed in, but the footer was something that needed to be
kept under the whole thing, so a clearing SPAN was placed under the list. Apart from that, the heading
was given a border and padding, the footer was given a background-color, padding, and text-indent. The
main paragraph also had its margins overridden (a P element usually generates margins above and below,
and none to the sides).
Believe it or not, this was actually tame coverage of the floating feature. There are countless ways to
‘hack’ the float property to achieve all sorts of amazing things, if you’re willing to create different style
sheets for different browsers. The information in this article should give you plenty of new structuring
ideas to play with though, without having to go into grey areas. There’s a lot of experimentation to be
done with the float property, and checking your results in different browsers is a must in this case.
Happy Floating!
Styling Forms
Form and Function
Forms are notoriously rebellious when the time comes to dress them up in eveningwear. Usually, when
you’re both the server-side programmer, and the client-side designer, by the time you get your PHP to play
nice with your MySQL, and your JavaScript to properly validate the form using Regular Expressions, you
haven’t got a single drop of sweat left to spare for making things pretty. But then, what does your user
see? Your user expects you to at least be competent enough for everything to work flawlessly, that’s a
given, it’s not like they’re going to go over your code and say “now there’s some elegant problem-
solving”... No, they judge your pages by what they see, and you bet that even a visitor that doesn’t know
what HTML stands for will be able to tell you if a form looks, feels, and behaves, like what they’d expect
from a modern website. They may not know the first thing about web development, but any user that’s
been online for more than 2 months—is an expert at filling forms.
Let’s face it, until personal data is properly standardized in such a way that with a few clicks we can
choose, on a sliding scale, exactly how much data, and which type of data, we let the website we’re
visiting have, we’re going to be building, and filling, a lot of forms.
First, let’s look at the initial form we’re going to be working with:
Customize your Avatar
Eye Color:
Avatar Class:
As you can see, it includes textboxes, radio options, and a select box. It also has an outline, which isn’t
the cause of any styling, but rather the effect of the FIELDSET tag (explained below). The gender option
selection area is italic, and that too isn’t the result of styling, but rather another tag—the EM tag this
time.
Let’s clear the whole thing up by going over the XHTML that makes up the form:
<div id=”theform”> <form action=”#” id=”form_nameb”> <fieldset> <legend>Customize your
Avatar</legend> <p><label for=”random_field_one”>Eye Color:</label> <input type=”text”
id=”random_field_one” name=”random_field_one” /></p> <p><label for=”random_field_two”>Hair
Color:</label> <input type=”text” id=”random_field_two” name=”random_field_two” /></p>
<p><span><em>Gender:</em> <input type=”radio” name=”gender” value=”male” checked=”checked”
/> Male <input type=”radio” name=”gender” value=”female” /> Female</span></p> <p> <label
for=”avatar_class”>Avatar Class:</label> <select name=”avatar_class”> <option>JavaScript
Juggler</option> <option>CSS Sorcerer</option> <option>PHP Phantom</option> <option>Perl
Prowler</option> </select> </p> <strong> <input type=”submit” value=”Submit Form” /> <input
type=”reset” value=”Reset Fields” /> </strong> </fieldset> </form> </div>
Before moving along, there are 3 tags in there that aren’t that widespread, so here’s a quick refresher of
what they do:
• <LABEL>: The LABEL normally encases plain text. Its for attribute associates it with either
an INPUT, a SELECT, or a TEXTFIELD’s id. Browsers react differently to LABELs, but the
id that matches the
desired effect is that when the labeled area is clicked, the form field with the
for attribute’s value will gain focus. This works in modern browsers, but the feature should not
be counted upon for any scripting purposes. We’re using the tag here mainly for its compliance
with the standard structure of a form, and, of course, to shower it with CSS properties.
• <FIELDSET>: The FIELDSET simply groups form items. Unstyled, it has the very basic
LEGEND.
visual effect of a single-pixel black border. It also “has” the directly-related tag:
• <LEGEND>: The LEGEND is quite odd for XHTML. It must appear right after the opening
FIELDSET tag, and though it’s supposed to contain only text, it encases it instead of having it
as an attribute value. One wonders why the FIELDSET doesn’t simply have a LEGEND
attribute—possibly to allow us to style them separately, and we certainly will.
Now that we’re up to date, look over the structure of the above form. There may not be tables, but there
sure are a lot of wrappers up there. The form itself is encased with the DIV we’ll be styling. It also
contains, right within it, the FIELDSET and LEGEND elements, so you can mentally put those aside for
now. What you’re left with is the section for each input element/group: two separate textboxes, the dual-
radio buttons, and the SELECT box. There’s also the submit and reset buttons which are encased with
STRONG elements.
The textboxes each have a LABEL next to them (actually, preceding them), and associated with them.
Each textbox and its LABEL is then encased with a P element.
The radio buttons are a bit more involved, because the text next to them, as well as the text denoting
their category, is in “free space”. You can’t associate a LABEL with a radio button group, even though
there’s nothing really preventing you from placing one next to them. However, if it’s not going to have a
specific active function, there’s no need to suggest to any browser that there’s another active element to
worry about. The area in this case, within the P element, that is, is encased with a SPAN. SPAN is CSS’s
favorite tag: it does nothing at all. It just sits there, waiting to be flavoured - like tofu. In this case, it
doesn’t even need a class property, it’s nested enough so that selecting it with a style rule it will be easy
and specific. Within the SPAN, there’s an EM element encasing the word “Gender”. Why EM? because
it’s a passive tag—when it’s unstyled it emphasises the encased text, usually by making it italic, though
that’s not strictly in the standard. It’s there to be styled, so we can use another type selector instead of
using a class. But then, what’s with the form_font class? Unfortunately, Explorer 6 won’t apply fonts to
That about covers the structure of the form. Once you understand the concepts of CSS selectors and
how/when to use classes and tags, you’ll be able to easily create your own table-less structures. In the
meantime, these are building blocks you can mold using CSS to any style you require.
The first properties that were set were the font-family, font-size, line-height, color (for the text) and width
of the theform id style rule. This is a typical property group for a DIV that doesn’t include positioning
elements, so there’s no need to expand here. The second style rule selects the FIELDSET, and sets the
background, and the border. As you can probably deduce from looking at how the form looks unstyled, the
border refers to exactly what you’d imagine—the visible 1px black border that normally appears with the
unstyled FIELDSET. Setting the border here will address that specific border, which is very convenient,
since it happens to perform a neat trick: it goes right through, and underneath, the LEGEND’s element’s
area. Sure, you could create that effect artificially using CSS, but you get it for free here, and it’s quite
simple to get rid of the effect, or alter it, if you wish. Now we laden the LEGEND style rule with a whole
lot of properties, though really, most are Box Model properties: border, padding, and margin. The others
are the background, and the font.
Now let’s stop for a moment and see what this looks like independently from the rest of the form:
Customize your Avatar
Some text inside the fieldset area.
Pretty fancy for 3 elements (we don’t style the form, it’s invisible here). You can now see why it was
important to separate the vertical and horizontal padding for the LEGEND—it gives an overall better
effect than a uniform padding, though you might want to use the shorthand version in your
implementations. The LEGEND was also shifted to the right using margin-left, and its border was set to
2px. As you can see, the LEGEND is inherently a block-level element, what with it wrapping a block of
HTML, again making it very convenient for us to style.
LEGEND and design it to attach to the
Don’t like rectangles? Place an background-image in the
FIELDSET border. CSS gives you many ways to misbehave.
Next up, the textboxes:
#theform p { margin-bottom: 4px; margin-top: 4px; } #theform p input { background: #DDD; border:
1px solid #444; } #theform label { display: block; width: 120px; float: left; text-align: right; padding-
right: 10px; }
This achieves several things. First, we’re separating theINPUT fields from each other, using margins
(technically, it’s theP elements we’re separating). Mind you, margin-collapse does take place here. Next,
we’re getting rid of the bevel (on some platforms) on the textboxes in favor of a 1px black border, and a
grey background.
The interesting part, though, is the LABEL style rule. First, it’s turned into a block-level element using the
The first two rules up there are obvious—we’re styling the buttons to match the textfields. The second two
rules are the interesting bit. This time, it’s the EM that is becoming a block-level element, and is floated
left. This is exactly what was done with the LABELs previously. This time around, there’s no LABEL, but
there’s an EM within a SPAN, so it’ll do.
The resulting form:
Customize your Avatar
Eye Color:
Hair Color:
Avatar Class:
And the many CSS style rules that come with it:
#theform { font-family: Trebuchet MS, sans-serif, Arial, Helvetica; font-size: 14px; line-height: 1.2em;
color: #444; width: 400px; } #theform fieldset { background:#FFF; border: 1px dashed #AAA; }
#theform legend { background:#DDD; border: 2px solid #CCC; padding-top: 2px; padding-bottom: 2px;
padding-left: 15px; padding-right: 15px; margin-left: 25px; font-weight: bold; font-size: 16px; }
#theform p { margin-bottom: 4px; margin-top: 4px; } #theform p input { background: #DDD; border:
1px solid #444; } #theform label { display: block; width: 120px; float: left; text-align: right; padding-
right: 10px; } #theform p span em { display: block; width: 120px; float: left; text-align: right; padding-
right: 10px; font-style: normal; } #theform p span input { vertical-align: middle; border: none;
background: none; } #theform strong { margin-left: 100px; } #theform strong input { background:
#DDD; border: 1px solid #444; font-weight: bold; color: #444; margin-top: 10px; }
If you’re wondering about the overall size of the CSS here, create the same form using tables, and
compare the two. Then, create a form with 3 times the input fields, using tables. See where I’m going
with this?...
There was a single DIV, one id selector, and no tables used. This is what happens when people don’t
bother going over the W3C specs properly. It’d help if they weren’t miles long, but still, you see what I
mean.