Create CSS-dropcaps with the :firstletter pseudo element: Part 1
Now that more and more users have migrated to modern browsers such as Internet Explorer 6.0 and Netscape 7.0, developers have a bit more freedom in their use of aspects of CSS2. The :firstletter pseudo element offers one such example.
In short, this element lets you format the first letter of the element to which you attach it. So, for instance:
p:firstletter
would refer to the first letter of every <p> tag; while
#myIntro:firstletter
would refer to the first letter of the myIntro element only.
With this element at our disposal, however, we can now create dynamic dropcaps--that is those not tied to an image of any kind.
To create a drop cap in its most basic form, you simply assign a larger font-size to the :firstletter element. The following code shows how you might implement this element in a Web page:
<html>
<head>
<style type="text/css">
.intro1:first-letter {font-size: 3em;}
</style>
</head>
<body>
<h3>The Rights of Man</h3>
<p class="intro1">Hitherto Mr. Burke has been mistaken and
disappointed in the opinions he had formed of the affairs of
France; but such is the ingenuity of his hope, or the malignancy
of his despair, that it furnishes him with new pretences to go
on. There was a time when it was impossible to make Mr. Burke
believe there would be any Revolution in France. His opinion then
was, that the French had neither spirit to undertake it nor
fortitude to support it; and now that there is one, he seeks an
escape by condemning it.</p>
</body></html>
Hitherto Mr. Burke has been mistaken and disappointed in the opinions he had formed of the affairs of France; but such is the ingenuity of his hope, or the malignancy of his despair, that it furnishes him with new pretences to go on. There was a time when it was impossible to make Mr. Burke believe there would be any Revolution in France. His opinion then was, that the French had neither spirit to undertake it nor fortitude to support it; and now that there is one, he seeks an escape by condemning it.
Notice that we used EM units to set the font-size. This way, the dropcap will scale appropriately if the user adjusts the page's text size settings via their browser.
********** THE TIP **********
Create CSS-dropcaps with the :firstletter pseudo element: Part 2
In part 1 of this tip, we showed you how to create a dropcap using the CSS2 :firstletter element. If you viewed the HTML we provided, however, while the first letter was much larger than its associated text, it stood above the first line of content. As you know, a dropcap typically sits below the first line.
Fortunately, we can easily create a true dropcap with a the addition of two familiar CSS2 properties. First, aside from enlarging the first letter's font-size, we also want the subsequent text to wrap around it. The float property provides the perfect avenue for doing so. If we float the first letter to the left, than all the text that follows will wrap around it, as seen if you open the following Web page in a supporting browser:
<html>
<head>
<style type="text/css">
.intro2:first-letter {
font-size: 3em;
float: left;}
</style>
</head>
<body>
<h3>The Rights of Man</h3>
<p class="intro2">Hitherto Mr. Burke has been mistaken and
disappointed in the opinions he had formed of the affairs of
France; but such is the ingenuity of his hope, or the malignancy
of his despair, that it furnishes him with new pretences to go
on. There was a time when it was impossible to make Mr. Burke
believe there would be any Revolution in France. His opinion then
was, that the French had neither spirit to undertake it nor
fortitude to support it; and now that there is one, he seeks an
escape by condemning it.</p>
</body></html>
Hitherto Mr. Burke has been mistaken and disappointed in the opinions he had formed of the affairs of France; but such is the ingenuity of his hope, or the malignancy of his despair, that it furnishes him with new pretences to go on. There was a time when it was impossible to make Mr. Burke believe there would be any Revolution in France. His opinion then was, that the French had neither spirit to undertake it nor fortitude to support it; and now that there is one, he seeks an escape by condemning it.
If you view this page, you'll notice that there's very little space between the new dropcap and the following text. To add a bit of whitespace, you can also apply a bit of padding to the :firstletter element. We've found that .1em works well for this property:
padding-right: 0.1em;
********** THE TIP **********
Use CSS groups with shared style settings
In a previous tip, we showed you how to use CSS groups to consolidate CSS style declarations, as in:
class1, .class2, #elem3 {border:solid 2px blue}
Often however, you may have elements that don't have exactly the same style declarations, but still share some common traits. For instance, consider the following CSS styles:
title {font-weight:bold; width:80%; color:blue;
font-size:1.5em}
heading1 {font-weight:bold; width:80%; color:blue;
font-size:1.2em}
In cases like this, where the elements require much of the same styles with minor modifications, it's still worthwhile to combine those settings the elements share, and seperate those they don't, like so:
title, .heading1 {font-weight:bold; width:80%; color:blue;}
title {font-size:1.5em}
heading1 {font-size:1.2em}
Doing so helps keep your code organized and compact. Also, if you decide later to change the overall style of your site--all titles and headings will be green, for instance--you only need to change a single group setting, rather than hunting down each individual element's style declaration.
********** THE TIP **********
Use the @media print CSS declaration to adjust print styles
Chances are, there will be times when you'll need to create a printer-friendly version of a Web page. For instance, many intranet developers often duplicate corporate forms on a Web page that need to be printed.
In such cases, some Web page elements become extraneous when printed--form fields come to mind. Fortunately, you can use the @media print CSS declartion to tell the browser what to do during a print. In this case, we could hide any form fields we didn't want on the final printout, like so:
<html>
<head>
<style type="text/css">
@media print {
#button1 {display:none}
}
</style>
</head>
<body>
<h2>This is the part to be printed....
<script type="text/javascript" lang="javascript">
document.write(navigator.userAgent)
</script>
</h2>
<form>
<input type="button" id="button1" value="Click Me"/>
</form>
</body>
</html>
********** THE TIP **********
Use CSS groups with shared style settings
In a previous tip, we showed you how to use CSS groups to consolidate CSS style declarations, as in:
class1, .class2, #elem3 {border:solid 2px blue}
Often however, you may have elements that don't have exactly the same style declarations, but still share some common traits. For instance, consider the following CSS styles:
title {font-weight:bold; width:80%; color:blue;
font-size:1.5em}
heading1 {font-weight:bold; width:80%; color:blue;
font-size:1.2em}
In cases like this, where the elements require much of the same styles with minor modifications, it's still worthwhile to combine those settings the elements share, and seperate those they don't, like so:
title, .heading1 {font-weight:bold; width:80%; color:blue;}
title {font-size:1.5em}
heading1 {font-size:1.2em}
Doing so helps keep your code organized and compact. Also, if you decide later to change the overall style of your site--all titles and headings will be green, for instance--you only need to change a single group setting, rather than hunting down each individual element's style declaration.
********** THE TIP **********
Add CSS padding to an image in MS IE 5.x
If you've ever tried to use CSS to add padding to an image, you may have been surprised when you viewed the page in IE 5.x (or IE 6.0 in non-standards mode). These browsers ignore the padding property when it's applied to images. As a work-around for this behavior, wrap the image in a container element, and then apply the padding (and any margins, as well) to the container object instead of the image. The following code shows an example of this work-around.
<html><head>
<style type="text/css">
#img1 {
float:left;
border:solid 2px black;
padding:1em;
margin-right:1em;
margin-bottom:1em;}
#img1 img {width:150px;}
</style></head>
<body>
<div>
<div id="img1"><img src="../images/pcah1.gif"/></div>
Here's some image to illustrate the padding and margins.
</div>
</body>
</html>

********** THE TIP **********
Keep CSS-floated elements on the same line regardless of font size
In some instances, you'll want several CSS-floated elements to remain on the same line - regardless of the browser window width OR the size of the font. As you know, under normal conditions, changes to the browser window width or the page's font size may force elements to wrap to a lower line.
If you only had to worry about changes to the browser window's width, then you could simply wrap the floated elements in a fixed width element, as seen in this XHTML:
<html>
<head>
<style type="text/css" rel="stylesheet">
.child {width:50%;float:left;border:solid 1px black;text-align:center}
.parent {width:200px}
</head>
</style>
<body>
<div class="parent">
<div class="child">Element K Journals</div>
<div class="child">Inside Web Development</div>
</div>
</body>
</html>
However, given this code, if the user increases the page's font size, the browser will automatically push the content beyond the window's right side; thereby forcing the content to wrap.
To fix this behavior, you can use EM units to create elements that expand along with the page's base font-size. The following XHTML shows how his works:
<html>
<head>
<style type="text/css" rel="stylesheet">
.child {width:9em;float:left;border:solid 1px black;text-align:center}
.parent {width:18em}
</style>
<body>
<div class="parent">
<div class="child">Element K Journals</div>
<div class="child">Inside Web Development</div>
</div>
</body>
</html>
Notice that in both cases, the wrapper parent
********** THE TIP **********
Use CSS to center a table in NN 6.2+, Mozilla 1.0, Opera 5.0+, and IE 5.0+
In NN 6.2+, Mozilla 1.0, and Opera 5.0+ centering a table couldn't be easier. To do so, simply assign table's CSS margin-right and margin-left properties to auto, like so:
<html>
<head>
<style type="text/css">
table
{
margin-left: auto;
margin-right: auto;
text-align: left;
}
</style>
</head>
<body>
<table>
<tr><th>Monday</th><th>Tuesday</th></tr>
<tr><td>3,333</td><td>400</td></tr>
</table>
</body>
</html>
When you do, these browsers center the table as expected. Unfortunately versions of IE 5.x (or 6.0 in 'quirks' mode) don't recognize these properties when it comes to tables.
For, versions of IE, to center a table, simply wrap it in a container
<html>
<head>
<style type="text/css">
table
{
margin-left: auto;
margin-right: auto;
text-align: left;
}
.tableDiv
{
text-align: center;
}
</style>
</head>
<body>
<div class="tableDiv">
<table>
<tr><th>Monday</th><th>Tuesday</th></tr>
<tr><td>3,333</td><td>400</td></tr>
</table>
</div>
</body>
</html>
********** THE TIP **********
Gain control of graphical bullets with a miniature 2-column CSS structure
As you know, the UL, OL and LI tags have been around since the birth of HTML. With the introduction of CSS, you can now quickly add graphic bullets to standard lists. Unfortunately, even with the new CSS list properties, developers still don't have the kind of control over the bullets that they may need, especially when it comes to a bullet's alignment in relation to its related text.
For example, often you may want a bullet to be vertically centered in relation to it's associated text--no matter how many lines of text each list item may cover. With a normal bulleted list, the bullets are restricted to the first line of text. Fortunately, with a simple modification to your HTML and CSS, you can create a list where the bullets are vertically centered with an entire passage, not just the first line. The following code shows how to achieve this effect:
<html>
<head>
<title>Vertically centered bullets</title>
<style type="text/css">
.rowItem {
position:relative;
margin-bottom:.75em;
width:20em;
padding-left:25px;}
.rowImage {
position:absolute;
top:35%;
left:0;}
</style>
</head>
<body>
<div class="rowItem"><img class="rowImage" src="../images/bullet.gif"/>
Inside Web Development will
provide you with the essential building blocks to help you build better Web sites. You'll
learn today's Web languages from the ground up and how to make the best use of all the
tools at your disposal across various browsers.</div>
</body>
</html>
Inside Web Development will
provide you with the essential building blocks to help you build better Web sites. You'll
learn today's Web languages from the ground up and how to make the best use of all the
tools at your disposal across various browsers.Notice that the bullet image's CSS top property now determines how it appears in relation to the text; while the percentage value ensures that the bullet placement remains consistent regardless of the length of each element. Simply change this percentage value to raise or lower the bullet image. The rowItem's padding ensures that the text associated with the bullet doesn't wrap around the graphic.
********** THE TIP **********
Include the closing </script> tag when using external JavaScript files
Under normal circumstances, when you use an external JavaScript file in a Web page, you could include it as an empty tag, as in:
<script language="JavaScript" type="text/javascript" src="someJS.js" />
However, due to a glitch in Netscape Navigator 6.2+ you must provide a closing tag, as in:
<script language="JavaScript" type="text/javascript" src="someJS.js" > </script>
Without the closing tag, NN 6.2+ won't recognize or include the external file.
********** THE TIP **********
Be aware that IE 5.x CSS properties may not cascade as you expect
In versions of Microsoft Internet Explorer 5.x (and 6.0 in non-strict mode), don't be suprised by unexpected cascade behavior when using CSS. One of the biggest offenders are tables. Styles set at a higher level of the document don't get inherited by a table. To see what we mean, open the following HTML page in a version of IE 5.x:
<html>
<head>
<title></title>
<style type="text/css">
body {font-weight:bold}
</style>
</head>
<body>
<div>This is a header!</div>
<table><tr><td>TCell</td></tr></table>
</body>
</html>
Normally, you'd expect all the text in the page to be styled bold. In fact, in conforming browsers like IE 6.0 (in strict mode) and NN 6.2, this is exactly what happens. In IE 5.x, however, only the text in the <div> is bold, while the content in the table remains unstyled.
********** THE TIP **********
Prevent floated CSS elements from overlapping in Netscape 6.2 and Mozilla
If you've tried to use floated objects in a Web page lately, you may have encountered an annoying glitch. If you float one block element next to another, Netscape 6.2 and Mozilla may run the non-floated content behind the floated content. To see what we mean, open the following code in a Web page:
<html><body> <div class="float" style="float:left;width:100px;height:100px;border:solid 2px black;">Float</div> <div class="nonFloat" style="position:relative;">No Float</div> </body></html>
When you open the Web page in NN 6.2 or Mozilla, the No Float element appears behind the Float element--not exactly the behavior it should have. The glitch apparently occurs whenever the non-floated item has a position:relative property assigned to it. If you remove this setting, the non-floated item wraps around the floated item as it should.
As a work-around, you have several options. First, you can remove this positioning only in NN 6.2 and Moz, like so:
body>.nonFloat {position:none}
In many cases, you'll want to keep the position:relative setting in place. If so, you can force the browser to place the element in a specific spot--or at least to adjust its placement, like so:
body>.nonFloat {margin-left:102px;}
This property assignment would bump the non-floated element over to the left to accommodate the floated element.
********** THE TIP **********
With the CSS url() function, paths are relative to the stylesheet
The CSS url() function provides a much-needed way to supply external files for use in a Web page. Most of the time, you'll use this function in conjunction with an element's background image. For instance, the following CSS:
#myElem {background-image: url(dog.jpg);}
would load the dog.jpg image into the background of the myElem element.
However, when using the url() function, keep in mind that while you can easily use relative file path, these paths are relative to the CSS stylesheet NOT to the HTML file to which the stylesheet applies. So, for instance, if the earlier dog image was stored in a folder named "images" and the CSS "stylesheets" folder was a sibling of the "images" folder, then the relative path to dog.jpg would be as follows:
#myElem {background-image: url(../images/dog.jpg)}
********** THE TIP **********
Two easy ways to ensure that your HTML and CSS is up to spec!
With as many hours as you spend coding your Web sites, it's only natural that errors will creep into your HTML or CSS. Fortunately, there are two Web sites that can help you get your code back within the guidelines.
The first is the Web Design Group HTML Validator, available at www.htmlhelp.org/tools/validator/. When you go to this site, simply enter the URL of the page you want to validate, click the Validate It! button, and voila, the site presents a lists of errors and warnings. The errors will be mistakes that will make your Web page break in browsers, such as not quoting attribute values. Others will be optional, such as missing alt attributes in <img> tags.
For CSS validation, head on over to
http://jigsaw.w3.org/css-validator/validator-uri.html.
Once more, you'll need to enter the URI that points to the CSS stylesheet in question. So, for instance, for a site www.BuggyBumpers.com with a CSS file located in the directory /stylesheets/main.css, you'd enter:
http://www.BuggyBumpers.com/stylesheets/main.css
As with the WDG site, when you submit this URI, the CSS validation page lists any errors and warnings.
********** THE TIP **********
An important difference between styling <a> and :link in CSS
No doubt, you've come across two different ways of styling an anchor tag via CSS. In some cases, you may see authors using the anchor tag itself as a selector, as in:
a {color:blue;font-weight:bold}
In other instances, they may have tacked on the :link pseudo-class to a CSS style, like this:
a:link {color:blue;font-weight:bold}
So, what is the difference between the two? It's an important one. When you style an anchor tag with CSS, as we did in the first style declaration, the browser applies that style to every anchor tag, whether that element acts as hyperlink or an anchor. The second CSS declaration only styles hyperlinks, not anchors.
********** THE TIP **********
CSS equivalents for a table's cellspacing and cellpadding attributes
In an effort to separate Web page content from formatting, you've probably decided to get rid of the cellspacing and cellpadding attributes in your <table> tags. But how do you replicate these same settings in a CSS stylesheet?
Unlike the attributes in question, which apply formatting to all cell types in an entire table, in CSS you'll need to format each type of cell (<td> and <th>) individually. So for instance, to give all cells (<td> or <th>) a border, you'd use:
td, th {border: solid 1px black}
A table cell's margin property provides the CSS equivalent to cellspacing, while the padding property equates to cellpadding. Given these properties, here's an example of how you might format a table:
<style type="text/css">
td, th {border: solid 1px black; margin:2; padding:5;}
</style>
<div>
<table>
<tr><th>ID</th><th>Name</th><th>Score</th></tr>
<tr><td>355</td><td>Ted</td><td>299</td></tr>
</table>
<font color=#000000>
</div>
********** THE TIP **********
Making sure a browser knows a CSS style is important
Under normal circumstances, a browser applies CSS styles in the order in which they appear in the stylesheet. For instance, in the following case:
div {background-color: red}
div {background-color:blue}
the browser would make the <div> element's background color blue.
Sometimes, however, you may want to provide an alternate style in case your first style choice doesn't work in a particular browser. For instance, while IE 5.5 supports a dashed border style, IE 5.0 doesn't. For IE 5.0 visitors, you may want to supply a solid border instead. However, if you supplied CSS style such as:
div {border-style:dotted;border-width:5px;border-color:black}
div {border-style:solid}
IE 5.5 or any other advanced browser will apply the solid style, since it appears last.
Fortunately, CSS's !important qualifier helps alleviate this problem. In essence, this qualifier tells the browser to apply a particular style above all others. To use this qualifier, you simply append it to the end of an individual property setting like so:
border-style:dotted!important
With this qualifier in place:
div {border-style:dotted!important;border-width:5px;border-color:black}
div {border-style:solid}
browsers that support the dotted border style will apply it, while those that can't will revert to the solid style.
********** THE TIP **********
When is a CSS containing block not a block that contains?
As you may know, according to the CSS specifications, browsers position even absolutely positioned elements relative to their containing block. A containing block is the ancestor of the element in question. So, for instance in the following XHTML:
<DIV> <div id="div1"> <div id="div2"/> </div> <font color=#000000></div> </div>
the div1 element contains div2, or div1 is the containing block for div2. As a result, when you style div2's dimensions or position coordinates, the browser calculates these values based on the containing block. For example, given the earlier XHTML, in the following CSS:
div1 {width:50%}
div2 {width:50%}
The browser will make div2's width 50 percent of div1's final width, or 25 percent of the entire page width.
Keeping this expected behavior in mind, open the following Web page in IE 5.0+ or NN 6.2+:
<div>
<div style="background-color:red; width:50%; height:100%; color:white">
This is the container.
<div class="box" style="background-color:green;">
This should be inside the red box.
</div>
</div>
<div class="box" style="background-color:yellow; top: 30%;color:black">
This should be outside the red box.
</div></div>
However, when you open the page, the two browsers position both the green box and the yellow box outside the red box, at the browser window's 50 percent mark. Since the red box contains the green box, however, we'd expect the green box to be inside the red box, with its left edge at the halfway point.
You can find the reason for this behavior in an easy-to-miss section of the CSS spec. It reads:
"Definition of "containing block" If the element has 'position: absolute', the containing block is established by the nearest ancestor with a 'position' other than 'static' ... If there is no such ancestor, the content edge of the root element's box establishes the containing block."
This means that in order to designate an element as the containing block for absolutely positioned elements, you *must* set its position property. In our example, we didn't do this, so the containing block defaulted to the <body> element. If we change the red box's element to:
<div style="position:relative; background-color:red; width:50%; height:100%">
the browser positions and sizes the elements as expected.
<div style="position:relative; background-color:red; width:50%; height:100%; color:white;">
This is the container.
<div class="box" style="background-color:green;">
This should be inside the red box.
</div>
</div>
<div class="box" style="background-color:yellow; top: 30%;color:black">
This should be outside the red box.
</div>
********** THE TIP **********
Add drop shadow to text using CSS
| <div ID="dropText" STYLE=" width: 210; height: 10; font-size: 16pt; align:right;font-family: Verdana; color: #000040; filter: dropShadow(color=#C0C0C0, offX=3, offY=3, positive=1) ">Sample Shadowed TEXT < /div> |
Sample Shadowed TEXT |
********** THE TIP **********
Don't forget to use units in CSS
Internet Explorer browsers are notoriously easy-going when it comes to putting unit indicators after CSS properties. For instance, even IE 6.0 will accept the following property setting:
<style type="text/css">
.someClass {border:solid 6 green}
</style>
even though the border's width value (6) doesn't indicate what unit to use. In the absence of a specific unit, IE will use a default. Other browsers, however, like Mozilla and Netscape Navigator 6.0+ won't. Instead, they'll ignore the property setting all together. With this behavior in mind, make sure to add units where appropriate to all your CSS properties.
********** THE TIP **********
Assign multiple CSS classes to a single HTML element
You're probably familiar with the standard way to apply CSS classes to an element. The most common way to do so is to simply assign the class name to an element's class attribute, as in:
<p class="para">Some important text.</p>
However, the CSS2 spec also provides another way to assign class names. According to CSS2, an element will belong to a CSS class when "the element's attribute value is a space-separated list of 'words,' one of which [matches the class name]." In plain English, this means that a Web page element can contain a space-delimited list of class names. CSS2-comforming browsers will apply all indicated classes to the element. So, for instance, given the following element:
<div class="para paraAlt">Some important text!</div>
A CSS2-conforming browser would apply both para and paraAlt style properties to the element.
********** THE TIP **********
These days, browsers support most, if not all, of the CSS1 specification. However, if you find that you need to build a page that supports older browsers such as Netscape 4.7, then you can take advantage of the W3C test suites for CSS1. These suites display a series of formatted CSS1 elements, as well as describe how they should appear on the page. If the formatted elements don't appear correctly, then you know the clunky old browser doesn't support that particular CSS1 property. You'll find it at the W3C site: http://www.w3.org/Style/CSS/Test/CSS1.
The W3C has broken down the test pages into sections, according to the CSS1 groupings. Sections include tests for pseudo-elements, font, text and box properties. When viewing the test pages, the top section displays the CSS styling that's being tested, while the lower portion describes what you should be seeing in the browser window.
********** THE TIP **********
How to put a border around a Navigator 6.0 link image
You'll often want to use a link as an image, whether it be to provide a fancy button, or simply a thumbnail link to a larger picture. To do so, you might use the following XHTML:
<a href="/images/downbutton.jpg"> <img class="pic" src="/images/upbutton_thumb.jpg" align="top" alt="greek3"/></a>
In addition to the link behavior, you may also want a dynamic border as the hover effect. For instance, when the mouse pointer hovers over the image, you may want it enclosed in a red border. At all other times, you want a blue border. Given the above XHTML, to provide a border around the anchored image, you might think to create a style declaration like so.
<style type="text/css">
<!--
a {border:solid}
a:visited {border-color:blue;}
a:link {border-color:blue;}
a:hover {border-color:red;}
-->
</style>
Unfortunately, this wouldn't work quite as expected in NN 6.0. That's because NN 6.0 doesn't expand an anchor tag to encompass the image, so the anchor border appears as a flattened rectangle at the bottom of the image. To circumvent this behavior, add the CSS style declarations to the pic class instead, like so:
<style type="text/css">
a.pic {border:solid}
a.pic:visited {border-color:blue;}
a.pic:link {border-color:blue;}
a.pic:hover {border-color:red;}
</style>
<a href="/images/downbutton.jpg" class="pic"><img src="/images/upbutton.jpg" align="top"
alt="greek3"></a>
Under this declaration, the image now has a border that not only fully encompasses the image, but also changes color when you hover the mouse pointer over it.
********** THE TIP **********
Place the a:hover pseudo-class last
For anchors, CSS offers the pseudo-classes :hover, :visited and :link. These classes let you style the three stages of a link. Use :link to style the link before the user activates it. Use :hover to style the link when the cursor hovers over it, and use :visited to style the link after the user visits it. Typically you'll use all three classes in tandem, like so:
a {border:solid}
a:visited {border-color:blue;}
a:link {border-color:blue;}
a:hover {border-color:red;}
In NN 6.0, though, the :hover pseudo-class won't work properly unless it's the last declaration of the three. In IE 5.5, it simply has to follow the :visited class. However, since cross-browser is more important, simply place it after the other two.
********** THE TIP **********
Why the CSS text-align:center property may not work the way you think
When you use the CSS text-align:center property, keep in mind that this property only works on the element's subordinate children, not any text in the element itself. For instance, consider the following XHTML:
<style type="text/css">
<!--
.test {text-align:center;}
-->
</style>
<span class="test">This is some sample text</span>
With this code in place, you might expect that the browser would center the text in the <span class="test"> tag...but it doesn't. That's because the text within the <span> element itself, isn't a subordinate element.
To truly center the text, then, you must add the text-align:center declaration to the <div id="myDiv"> element, like so:
.test {color:white; text-align:center;}
#myDiv {text-align:center; position:absolute; top:10px; left:20px;
width:350px; height:250px; background-color:black;}
Doing so would center *all* child elements within the myDiv div.
********** THE TIP **********
Retrieve CSS computed style values in JavaScript
If you've ever tried to retrieve the CSS style value of an element via JavaScript, you know how frustrating it can be. While the major browsers let you access CSS style values declared in an element's style attribute (through the JavaScript style property), they don't let you access styles declared in a declaration block the same way. Fortunately, you *can* still access these values.
To do so, in IE 5.0+, use the currentStyle property in place of the style property, as in:
var elem2 = document.getElementById("para2")
document.write("<h4>Para2 font-size:" +
elem2.currentStyle.fontSize + "</h4>")
In DOM2 supporting browsers, such as NN 6.0+ and Mozilla, you need to take a different approach. These browsers support the getComputedStyle() function, which retrieves a style object that contains all the CSS style values *after* the browser has laid out the page. You use this function like so:
var elem2 = document.getElementById("para2")
var sElem2 = getComputedStyle(elem2,'')
var fSize = sElem2.getPropertyCSSValue
("font-size").getFloatValue(CSSPrimitiveValue.CSS_PT)
document.write("<h4>Para2 font-size:" + fSize + " pt</h4>")
First you obtain the style object, then get a specific property from it, and convert the property value into a specific data type (float or string, for the most part) and unit.
********** THE TIP **********
Obtain CSS style declaration values in DOM2-compliant browsers
With the release of Internet Explorer 5.0 and Netscape Navigator 6.0, you may have noticed some of your previous JavaScript code acting a little strange with regard to CSS style settings. The 4.x browsers flowed all CSS property values together, and then exposed these settings in JavaScript properties. No longer.
These days, the browsers separate the style settings between inline styles--those settings hard-coded into an element's style attribute-- and style declarations--those settings in a Web page's <style> block. You can access inline settings in JavaScript just like you always have, via the element's style property. However, reading style settings in a CSS declaration rule takes a little more work.
Of course, DOM2-compliant browsers make this job the easiest. When a browser loads a Web page, it of course must read the CSS style blocks and apply the values. The DOM2 makes these run-time values available in the ViewCSS object, as returned by the defaultView property. A DOM2 ViewCSS object represents the current layout of a Web page. This view may be static or dynamic depending on whether elements in the page have changed or not. As a result, the ViewCSS object always contains the most current CSS style property values applied to an element.
The getComputedStyle() method returns the style object associated with a specific element. This style represents *all* current settings associated with that object. To retrieve the object, you apply it to the document's default view, like so:
var tempStyle = document.defaultView.getComputedStyle(obj,null)
In the first parameter, you pass in the element for which you want to retrieve the computed styles. In our example, we passed in a generic variable named obj. Presumably, this variable would contain some Web page element. Most of the time, you won't use the second parameter, which should contain either null or the name, passed in as a string, of a pseudo-element.
Once your code has retrieved the style object associated with an element, it can access an individual property value with the getPropertyValue() method, which you'd use like so:
tempStyle.getPropertyValue("color")
which, when applied against the myElement above object would return the value red.
********** THE TIP **********
Provide hassle-free list markers with CSS1 list-style properties
Not only does CSS provide an easy, efficient way to style list items, but it also lets you easily switch a list from ordered to unordered without ever having to change XHTML tags.
As you may know, the CSS1 list-style-type property declaration determines what type of preset marker appears in front of each list item. The full list includes bullet shapes, such as discs, circles and squares, as well as standard outline symbols like roman numerals and letters.
This property is pretty straightforward. For instance, given the following XHTML:
<ol class="schedule"> <li>History</li> <li>Algebra</li> <li>English</li> <li>Art</li> </ol>
to add an upper-roman marker to each of the list items, you'd simply use the CSS declaration:
.schedule {
list-style-type: upper-roman;
}
This declaration produces numbered list items using Roman numerals (I, II, III, IV, etc). Even though we declared the style for the ordered list block, <ol>, the browser actually applies the markers to each individual list item. This is exactly what you'd expect.
In addition to the <ol> element, the previous list-style declaration would produce the same results with a <ul> element too. However, if for some reason you wanted to change the ordered list to an unordered list, CSS makes it simple--just change the style declaration. For instance, without changing the <ol> tag to a <ul> tag, we can still make the page display square bullets in the list simply by altering the style declaration like so:
.schedule {
list-style-type: square;
}
********** THE TIP **********
Let your CSS stylesheets degrade elegantly with @import
While the number of surfers still using browsers other than IE 5.0+, NN 6.0 or Opera is steadily decreasing, you may want to provide CSS stylesheets only to the latest browsers. Doing so prevents low-end browser users from seeing a broken page.
You'll be happy to know that to provide just the right CSS stylesheet for the advanced browsers, you won't need to resort to a fancy JavaScript browser sniffing routine. Instead, you can take advantage of CSS's own @import rule.
This handy rule imports an external CSS stylesheet into a page. It lets you modularize your Web site, and plug in only those stylesheets that you need into each page. So, for instance, if you had a stylesheet that applied to just the navigation bar of your site, you'd use the declaration:
@import "navbar.css";
This command must appear in the style block before any other style property blocks, like so:
@import "navbar.css";
#myNav {background-color:blue;}
However, as you might guess, browsers that don't fully implement CSS, like NN 4.7, simply ignore the command. As a result, you can place more advanced CSS properties into the external stylesheet and not worry about older browsers bombing because of CSS they can't understand.
********** THE TIP **********
Create <frame>-less frames with CSS overflow
CSS can help alleviate some common frame downfalls--JavaScript complexity and gateway page circumvention--while at the same time provide the same low-maintenance that attracted you to frames in the first place.
In CSS-conforming browsers, to clip a containing box's content, you use the overflow CSS setting. This property takes the values visible, hidden, scroll, auto and inherit. Browsers use the visible value by default, and as you can guess, this simply means they display any overflowing content. The hidden value, however, tells the browser to hide the extra content. Under such conditions, the user can't access it. To clip content and at the same time allow users to view all of it, there's the scroll (overflow:scroll) value. When browsers encounter this value, they add scrollbars to the appropriate viewport. The following CSS declaration shows how you might use this property to define a viewport on Web site:
#bodyContent {
margin-left:auto;
margin-right:auto;
padding-left:5px;
width:85%;
height:65%;
overflow:scroll;
text-align:left;
border:solid blue 1pt;
margin-bottom:5px;}
********** THE TIP **********
Use the media attribute to print CSS formatting
If you've ever print previewed a CSS formatted Web page, you may have been surprised to see that the page no longer contained any of your carefully crafted CSS formatting. That's because, by default, CSS formatting only applies to the screen rendering of a Web page.
To make sure a printer also applies CSS formatting to a page, you'll need to indicate to which media you want the formats to apply. To do so, add a media attribute to either the <style> or <link> tag, like so:
<style type="text/css" media="screen,print">
Now, when you print the Web page, the printer applies the CSS formatting as well.
********** THE TIP **********
Use the style object for cross-browser CSS positioning
Before the major browsers decided to implement standards (to a certain extent) each browser forced you to position elements via JavaScript by using proprietary properties, such as the infamous .pixelTop. Now, though, when you want to position an element dynamically in the major browsers, you should use the style object instead.
Each JavaScript DOM HTMLElement exposes this object. It contains all possible CSS styles, including positioning properties. To access these properties, first create an object based on the element, like so:
var elem = document.getElementById("myDiv")
Then, access the object's style object and the property you want to change, as in:
elem.style.left = "300px";
Be sure to include the units when you set these values, as they're now required on all CSS properties.
********** THE TIP **********
Position CSS-floated elements flush against the browser window
If you've ever floated a Web page element to the left or right of a Web page, you may have noticed rather peculiar behavior in IE 5.0+ or Opera 5.0: The element didn't sit quite flush against the browser's left or right border. Instead, you may have seen some extra padding of about five to eight pixels.
This behavior occurs because both IE and Opera have an internal, default style for the <body> element. In IE, the default <body> style adds a margin, while Opera adds extra padding. As a result, to fix this behavior in both browsers, add the following CSS declaration to your style sheets:
body {margin:0;padding:0}
********** THE TIP **********
Use the style object for cross-browser CSS positioning
Before the major browsers decided to implement standards (to a certain extent) each browser forced you to position elements via JavaScript by using proprietary properties, such as the infamous .pixelTop. Now, though, when you want to position an element dynamically in the major browsers, you should use the style object instead.
Each JavaScript DOM HTMLElement exposes this object. It contains all possible CSS styles, including positioning properties. To access these properties, first create an object based on the element, like so:
var elem = document.getElementById("myDiv")
Then, access the object's style object and the property you want to change, as in:
elem.style.left = "300px";
Be sure to include the units when you set these values, as they're now required on all CSS properties.