Trang chủ‎ > ‎IT‎ > ‎WEB PROGRAMMING‎ > ‎02 - CSS‎ > ‎

CSS step by step

Learn CSS step by step

This website is all about CSS, a key tool in web design. In case you’re not familiar with CSS: CSS is the sister technology to HTML that is used to style your web pages. The details are in the tutorial, but for now we can say that CSS can make your web pages look great!

Written with beginners in mind

As with all my writing, I tried to make this web design tutorial on CSS as easy as possible to follow. Instead of a boring-nerd centric style, I’ve used more of a conversational style.

This tutorial website is like anything else in life; you get back what you put into it. So if you really want to learn how to design great looking pages, resist the temptation to stop halfway to use a web design program like FrontPage or Dreamweaver. By finishing the tutorial you will gain a big advantage over all the others out there that gave up!

Don’t get me wrong, this stuff isn’t that hard; it’s just that some people are really lazy!

How this website is set up

The website has 3 major sections:

  1. The introduction to CSS
    We cover the basics and show you a few neat tricks.
  2. A complete CSS tutorial 
    We get down and dirty here giving you a solid foundation in CSS so you can use it in your own web design work right away!
  3. Additional CSS Resources
    Supporting articles on CSS web design and a link takes you to an active CSS forum where you can ask any questions you may have.

Once completed, you will have taken the next step towards total nerd glory with these articles on creating a pure CSS web page. Not just CSS styling, but CSS positioning too, that means no tables required!

Once completed, you will be creating pages in sophisticated ways that 99% of web designers don’t even consider! Needless to say, you will have an advantage over the competition. All this is 100% standards compliant and should work in 99% of browsers being used today.

CSS Basics

1. Centering Text with CSS: Centering text and other elements can easily be done with the CSS text-align property. It can be applied to a division, the p tag – pretty much any block-level element.

Applying this to an internal or external stylesheet: 

p {text-align: center;}

or this to inline styling:

<p style="text-align: center;">This is centered text</p>

will center your text.

2. The CSS Overflow Property

This is where the overflow property comes into play. As you see, there is no overflow property applied to the above, but the division is responding to the default, which is

div {overflow: visible; }

So I need to decide what to do with this overflow. One option is to hide it by applying ‘overflow: hidden’ to the CSS. In an internal or external stylesheet, the styling for our example division would then look like this:

div {
height: 100px;
width: 200px;
background: #EDEDED;
overflow: hidden;
}

Good news is that in addition to ‘visible’ and ‘hidden’, which we explored above, there are two additional values to chose from: ‘scroll’ and ‘auto’. ‘Scroll’ will create a horizontal AND a vertical scrollbar to the box, whether one is needed or not.

That doesn’t make much sense. Why put a scrollbar if there’s nothing to scroll to? But if you think that you would know, as you design your site, if your content will fit into its element or not, you are not 100% correct. Things may or may not fit when YOU look at them, but you can never be sure exactly how all the folks visiting have their settings adjusted and how things look to them. With that in mind

div {overflow: auto;}

is the perfect solution. A srollbar will appear if one is needed:

3. Styling a Horizontal Rule with CSS:

A quick and easy way to insert a dividing line into a website is with a horizontal rule, the hr tag.

This horizontal rule


was created by the following inline CSS:

<hr style="color: #f00; background: #f00; width: 75%; height: 5px;">

It could also be styled in your internal or external stylesheet (which is usually the better approach):

hr {
     color: #f00;
     background: #f00; 
     width: 75%; 
     height: 5px;
}

Note that color AND background-color are applied. This is necessary, as some browsers use the background-color, others (IE) the color element to apply color to the rule.

4. Styling iframes with CSSIf you still haven’t heard, hear it now: FRAMES ARE DEAD – well, technically, they are more like the undead – the zombies of webdesign. They should be gone and forgotten but refuse to stay buried. It’s much better not to use them.

However, there may be a situation, where inserting a separate html document into your page makes sense. And there’s an app for that: Iframes (aka inline frames). This code inserts a basic page into an html page:

<iframe src="http://www.killersites.com/">
<p>Your browser does not support iframes.</p>
</iframe>

At this point, there is absolutely no styling applied to the iframe, and it looks like this. Note the line regarding lack of browser support. Iframes are supported by all the major browsers, but it’s a good idea to add this for the odd browser that doesn’t.

While I am a strong supporter of using the HTML strict doctype and writing validating, standard-compliant code – iframes will not validate, which leaves us with two options: Either suck up the iframe-related validation errors or switch to HTML transitional doctype for the pages with iframes.

CSS gives you the power to dress your iframe up a bit. The following attributes are available:

  • src (the URL of your iframe)
  • longdesc (this specifies the URL of the iframe, but is hardly supported and can just as well be ignored)
  • name (obviously, the name of your iframe)
  • height (the height of your iframe)
  • width (the width of your iframe)
  • frameborder (1 or 0 – 1 is for yes, 0 for no)
  • marginheight (determines the top and bottom margin of your iframe)
  • marginwidth (determines right and left margins of your iframe
  • scrolling (Do you want a scrollbar? Yes, no, or auto – ‘Yes’, is obvious. ‘No’ should not be used – what if someone does not see the entire content? If this is set to ‘no’, that viewer can never get to the hidden parts of what you’re inserting. ‘Auto’ lets the browser decide if one is needed and seems the best option here to me.)
  • (align) – I’m just mentioning this for completeness; it has been deprecated. Don’t use it.

So this inline CSS:

<iframe src="http://www.killersites.com" 
name="Killersites.com" height="400px" width="700px" 
frameborder="0" marginheight="20" marginwidth="35" 
scrolling="auto">
<p>Your browser does not support iframes.</p>
</iframe>

Gives you that. And if you add a bit more CSS to the frame itself:

iframe {
 margin-left: 95px;
}

you can position the entire frame where you want it.

5. Changing the Font to All Caps with CSS; While text in general is hard to read when written in all caps – and considered the electronic version of yelling – using CAPS for emphasize is a handy tool.

Headers are a place where capitalization is frequently used. And to assure that your header is displayed uniformly throughout the site without having to worry about actually writing in all caps, just use CSS:

h1 {
text-transform: uppercase;
}

With this, everything that has the h1 tag applied, WILL APPEAR IN ALL CAPS.

Another interesting text-transformation property is "capitalize"

h1 {text-transform: capitalize;
}

With This, All Your Words Will Begin With A Capital Letter!

6. Adding more than one Background Image with CSS: At times, it makes more sense to use background images than to insert them directly into the page. And while each element – like your body tag – can hold only one background image, they can be applied to several elements.

But pretty much every selector can hold a background image. On THIS PAGE, I have added the image to the html tag, the body tag, and the h1 and h2 tags (these are ‘selectors’) – like so:

body {
	background: url(bgimage.jpg) repeat-y right;
}
 
html {
	background: url(bgimage.jpg) repeat-y left;
}
 
h1 {
	background: url(bgimage.jpg) no-repeat right;
}
 
h2 {
	background: url(bgimage.jpg) no-repeat left #ffc;
	padding-left: 250px;
	height: 150px;
}
 
#wrapper {
	padding: 0 250px; 
/*I'm using the right and left padding of the wrapper to keep
the content off the images */
}

Note that I’m a bit lazy at the moment, and am using the same image for all four selectors. Taking a closer look at each of them, also shows a bit more how things work:

The html tag (image displayed on the left) repeats the flower all the way down the monitor, regardless of how much content there is. Resize your window and see what happens.

The body tag, where the image is displayed to the right, only shows the image as far as the content goes.

The h1 tag only shows as much of the image as the space its content is taking up.

The h2 tag also has some height added to it (exactly 150px, the height of the background image), so it does show the entire image. I’ve also added the background color to more clearly demonstrate the space that’s taken up by h2.

7. Styling Lists with CSS: We’ve already discussed navigation lists and list bullet images, but sometimes, a list is just a list. There are two types – the ordered list and the unordered list. The ordered list counts the items; the unordered list marks the individual items with bullets or other markers. The HTML is simple.

<ol>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
</ol>
 
<ul>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
</ul>

And, without any styling applied at all, that looks Like This.

We can affect the list item markers with some simple CSS and the list-style-property controls those. For unordered lists, we can chose between ul styles: disc, square, circle, or none – which looks like this, or between ol styles: decimal, decimal-leading-zero, lower-roman, upper-roman, lower-alpha, upper-alpha, lower-greek, upper-greek, lower-latin, upper-latin, armenian, or georgian, which looks like that.

Other than that, we can style the ul tag and the li tag. Anything added to the ul tag, affects the entire list, where properties applied to the li tag will affect the individual list items. So this CSS

ul {
	background: #ffe566;
	padding: 25px;
}
 
ol {
	background: #828772;
	padding: 15px;
}
 
ul li {
	background: #fc6;
	margin: 5px;
}
 
ol li {
	background: #9cc;
	padding: 10px;
        margin-left: 35px;
}

will create that.

(Note that I had to add the ‘ul’ or ‘ol’ in front of the ‘li’ so I could target specifically either list’s items. Had I just used ‘li’, any styling would have affected all of them regardless.) … example: adding a larger font size to ‘just li’.

8. How to Add Borders to Images with CSS: Sometimes, a website design benefits when images have frames – or borders. One way to get them is one image at a time, using a graphics program. But there is a much faster way – with CSS!

This code:

<img src="image.jpg" width="350px" height="262px" 
alt="Rusty Stove in Luckenbach, Texas">

inserts a plain image into your page:

And if we add this to our CSS:

img {
border-color: #7d6b72;
border-style: solid;
border-width: 5px;
}

Then our image appears like this:

Actually, I would use shortcuts and write my CSS like this:

img {
border: 5px solid #7d6b72;
}

9. 3-Column-Layout: The three-column layout is probably the second most common layout used for websites. There’s usually a header and a footer – and then some content, maybe a sidebar for navigation, a column in the middle with some content info, and another column with some additional stuff, whatever that may be. What you put inside your columns doesn’t matter – the way to achieve the 3-column layout stays the same.

So let’s start with our basic HTML to put all the parts on paper — or in our case, on line. This is the basic outline of what’s between the body tags:

<div id="wrapper">
 
	<div id="header"></div>
 
	<div id="column-left"></div>
 
	<div id="column-center"></div>
 
	<div id="column-right"></div>
 
	<div id="footer"></div>
 
</div>

For the entire HTML code – to include some filler content – see Basic HTML – No Styling. To see the code of the example page, just right-click and chose “View Source” from the drop-down. Most browsers offer that feature.

And of course what we get, is NOT a 3-column layout. It’s just one division on top of the next. That’s because we haven’t gotten to the ‘with CSS’ part of the title of this post yet. So let’s already!!

First, and just to make things easier to see, I will apply the fixed width and center my page. Here’s a post with the finer details Center-aligning a Website right here already. Here is the CSS that does that:

* {
	margin: 0;
	padding: 0;
}
 
#wrapper {
	width: 980px;
	background: silver;
	margin: 0 auto;
}
 
#header {
	background: black;
	color: white;
}
 
#column-left {
	background: red;
}
 
#column-center {
	background: yellow;
}
 
#column-right {
	background: purple;
}
 
#footer {
	background: green;
}

(Please note that you should really be using hex or rbg color codes, but for the purpose of this demonstration, color names are just easier to deal with.)

And it looks Like This. Now we just have to get our columns to act like columns and line up next to each other. There are different ways to do this, but I prefer to just float them all. So we’ll give them all a width and add float: left; to our three columns:

#column-left {
	width: 250px;
	float: left;
	background: red;
}
 
#column-center {
	width: 480px;
	float: left;
	background: yellow;
}
 
#column-right {
	width: 250px;
	float: left;
	background: purple;
}

At this point, it’s important to be aware of a special characteristic of floats – I picture them as balloons – they float above our heads, without taking up any actual space among us. So just as you can place a box under a balloon without the two affecting each other’s space, our footer will act like the floated divisions are not even there, and line itself up neatly right under the header – where we do NOT want it to be. So we have to give the footer a special set of instructions:

#footer {
	clear: both;
	background: green;
}

and now the whole thing looks Like This. And there you have it!

A few things can go wrong, and here is some easy, preliminary damage control: If you see your columns NOT all sitting next to each other, it’s likely because the total sum of all their widths, paddings, and margins combined is GREATER THAN the width of their containing wrapper. So put one of your columns on a diet and cut its width down some – and things should fall into place beautifully. And if not, ask for help at the Killersites Community.

10. CSS Comments: Comments in a stylesheet are a good idea. Often, things that are obvious as you write them, make no sense a week or even years later – or to somebody else. So it can be very helpful to include explanations. However, we don’t want to browser to read and render those, as they are not meant to be displayed on the webpage, so we have to hide them.

/*
This is a HIDDEN Comment!
*/

That’s all it takes – a ‘/*’ to start, and a ‘*/’ to end. A few handy applications for these hidden comments are:

h1 {
color: #000000; /* black - because I forget */
font-size: 2em;
}

Another handy use for the comments are to help define the structure, so things are easier to find:

/* ----------------- Generic Styles ------------------ */
 
.alignleft { float: left;}
.alignright { float: right;}
.clear { clear: both;}
 
p { margin: 0 15px 10px;}
 
h1, h2, h3 {
	font-family: Baskerville, Garamond, Palatino, "Palatino Linotype", "Hoefler Text", "Times New Roman", serif;
}
 
h2,  h2 {
	margin: 25px 20px 5px;
	color: #9e6548;
	font-size: 2em;
}
 
h3 {
	margin: 25px 0 5px;
	padding: 5px 25px;
	background: #9e6548;
	color: #f7efe3;
}
 
ul { margin-bottom: 25px; }
 
/* ----------------- The Header -------------- */
 
#header {
	background: url(pics/stove.jpg) #f7efe3 no-repeat top right;
	height: 200px;
	-moz-border-radius: 20px;
	-webkit-border-radius: 20px;
	border-radius: 20px;
}
 
#header h1 {
	color: #9e6548;
	font-size: 3em;
	padding: 35px 25px 0;
}
 
/* ------------- Top Navigation ------------------- */
 
#topnav {
	background: url(pics/nav.png) repeat-x;
	font-family: Geneva, Arial, Helvetica, sans-serif;
	font-size: 1.2em;
	font-weight: bold;
	width: 679px;
	height: 45px;
	top: 55px;
	position: relative;
	padding-top: 13px;
}
 
#topnav li {
	display: inline;
	margin: 15px;
	}
/* ------------ content -------------- */
 
#content, #contentPage, #indexPage {
	float: left;
	width: 635px;
	padding: 35px;
}
 
#contentPage h2, #search h2 {
	margin-top: 0;
	margin-bottom: 0;
}
 
#contentPage h3, #search h3 {
	margin-bottom: 10px;
}
 
/* ----------- Sidebar ---------------- */
 
#sidebar {
	width: 205px;
	background: #9e6548;
	float: right;
	margin: 12px 0;
	color: #f7efe3;
	padding: 20px 10px;
}
 
#sidebar h1, #sidebar h2 {
	font-size: 1.4em;
	margin: 25px 5px 5px;
	color: #f7efe3;
}
 
/* ------------- footer ----------------------- */
 
#footer {
	clear: both;	
	height: 40px;
	font-size: .8em;
	background: #9e6548;
	color: #f7efe3;
	text-align: center;
}
 
#footer p {
	padding-top: 14px;
}

I’m sure you get the idea.

11. How to Position Text around an Image with CSS: It’s always nice to have some pictures to go along with your text. However, if you just use the html to insert a photo into your text flow, you’ll find that it breaks up the flow of your text and just plops itself ungracefully right in the middle of your paragraph without rhyme or reason.

Fortunately, a little bit of CSS positioning can help us out here. Adding this to your CSS:

img {
	float: left;
}

will make the same thing look like this.

Now all we have to do is add some margin or padding to create a bit of space around the image

img {
	float: left;
	padding: 0 25px 25px 0;
}

And here you go.

However, if you use the image tag for your CSS, all the images in your site will float. Since this is a Basic CSS tip, I’ve used it for demonstration purposes only. A more practical approach would be to add a special class to the images you want to float.

<img class="floating" src="http://www.csstutorial.net/wp-content/uploads/2010/03/leia.jpg"
 alt="German Shepherd taking a nap">

and write the CSS like this:

img.floating {
	float: left;
	padding: 0 25px 25px 0;
}

12. How to Use CSS to Display Bullet Images: 

With CSS, you have several options for styling list bullets. For example, disk, circle, square, etc. But what if you want to use a specific image for your bullet? With CSS, you can do just that.

The code for your basic, unordered list, is this:

<ul>
<li>List Item 1</li>
<li>List Item 2</li>
<li>List Item 3</li>
<li>List Item 4</li>
<li>List Item 5</li>
<li>List Item 6</li>
</ul>

And it creates your Basic Unordered List.

In order to display a custom bullet image, we add this to our CSS:

ul {
         list-style-image: url(flower.gif);
}

Which gives us a list which looks like this. And you will notice a problem – my flower and my text just don’t line up properly. That is, they align at the bottom and not vertically centered as one would expect. I guess we could make the image smaller, but at that rate, it would have to be so small, nobody can see what it is, and we might as well use a standard circle. Or we can increase the font size, but that probably won’t work in relation to the rest of the design. Adding padding or margin would not help, either, as that adds to both the bullet image AND the text at the same rate, and neither would increasing the line height.

So while we wait and hope for some future development to address this issue, we have a way now to get this to look right. First, we get rid of our bullets altogether:

ul {
	list-style-type: none;
        line-height: 350%;
}

Note that I’m also increasing the line height, which may or may not be necessary, depending on your font size in relation to your image size. If you need line-height, you’ll just have to play around a bit until things look right. And then, we add a background image to our list:

li {
	background: url(flower.gif);
}

but if this is all we do, we end up with our flower across the entire line and with our text sitting on top of it. So we also need:

li {
	background: url(flower.gif) no-repeat center left;
	padding-left: 70px;
}

The ‘no-repeat’ tells our image to do exactly that, the ‘center left’ positions the image vertically centered and left aligned, and in order to get the text to move NEXT to the image, I’ve added some padding. And here you have a Perfectly Styled List Using Bullet Images, just not achieved quite the way you might have first expected.

13. Styling Fonts with CSS

The FONT tag is dead. Long live CSS! Please help spread the word, too many people STILL have not gotten that memo and merrily use their deprecated font tags (along with the table-based layouts and improper doctypes). But now we all know – no more excuses.

The easiest way to apply a font style to your website, is right there with your body tag:

body {
font-family: "Times New Roman", Times, serif;
}

And there you have it – now all the text on your page will be Times New Roman, and if that font is not installed on the viewer’s computer, then they’ll see the text in Times, and if they don’t have that either, then the text will display in whatever default serif font they have installed.

Side Note: Serif is the style with little hooks – for example  opposed to  (which is shown in Arial – see the difference?).

Do note the quotes around “Times New Roman” in the CSS above – that’s because that font name consists of more than one word. The quotes keep it together.

Sometimes, you may not want your entire page in one font, but might want your headers to stick out. Easy enough, just style them separately:

h {font-family: Verdana, Arial, Helvetica, sans-serif;
}

14. Styling different links differently with CSS

On a website, you often have different groups of links that may not all supposed to be looking the same. Usually, you’ll have navigation links and possibly some links within your content at a minimum. The post Styling Links with CSS shows how to style links in general. But how do you get your navigation links to look different than your content links and those different than your footer links (for example)?

Pretty simply, actually!

It will require some HTML and CSS coordination/cooperation, but then, that’s how everything on the site works anyway. So if you style your links just like this:

a:link {color: red;
background: yellow;
}
 
a:visited {
color: yellow;
background: red;
}
 
a:hover {
color: blue;
background: green;
}

(Note – It’s better to use hex-colors, but for this demonstration, color names make things more obvious. And we could also style the link for the active and focus status, but that is not relevant for the purpose of this tutorial.)

So if we add the above to our CSS, all the links in the entire document will look the same – like so.

To create the distinction, I’m adding the ID of ‘navigation’ to the navigation. To see the html for the sample page and for any webpage in your browser, right-click anywhere on your site, and ‘View Source” should be an option available in the drop-down your right-click provides. The footer already has an ID of ‘footer’, and the links in the content, we’ll leave alone. And we add to the above CSS this:

#navigation a:link {color: pink;
background: purple;
}
 
#navigation a:visited {
color: purple;
background: pink;
}
 
#navigation a:hover {
color: white;
background: teal;
}
#footer a:link {color: yellow;
background: black;
}
 
#navigation a:visited {
color: black;
background: aqua;
}
 
#navigation a:hover {
color: red;
background: silver;
}

And there you go ….

15. Adding a Background Image with CSS

Background images, just as the name implies, are part of the BACKGROUND of a website, not part of the actual content. The most common place to add a background image to, is the entire canvas – aka the body tag.

The CSS to add an image to a body tag is simple:

body {
background: url(bgimage.jpg);
}

I’m just using a random image for demonstration purposes, and THIS this is what we get. And we can note the following:

  1. It’s a very beautiful flower (grew in my house)
  2. It repeats itself and covers the entire background – that is called ’tiling’ (think bathroom)
  3. It pretty much makes it impossible to read the actual page content

There are also special background images that are designed to tile unnoticeable -for example this one:
Background Image optimized to tile unnoticeable  which will create THIS.

CSS also gives us the tools to direct our background image how we want it. The default, as you can see, is that it repeats itself horizontally AND vertically to fill the entire background, regardless of size. Sometimes we might want the image appear only horizontally or vertically – and maybe not directly on the edge of the viewing area.

body {
background: url(bgimage.jpg) repeat-x bottom;
}

creates a background that is repeated vertically at the bottom of the content, and this background image repeated horizontally on the right is created by this CSS:

body {
background: url(bgimage.jpg) repeat-y right;
}

There are many more ways for us to control our background. In addition to the above, we could:

  • Add a background color (background: url(image.jpg) #555555;)
  • Display the image only one time (no-repeat)
  • Position it more specifically (options are: top, bottom, left, right, center, x-15px, or y-20% (measurements and units are optional))
  • Keep it from scrolling (background: url(image.jpg) fixed;)
  • Any combination of any of the above

A wise combination of all these techniques might actually allow us to create a decorative background that does NOT interfere with the actual content. Like This. The following CSS created this page – and please note that I also added some padding to keep the content off the image, which makes things soooo much easier to read:

body {
	background: url(bgimage.jpg) no-repeat #f6f1b9 fixed top right;
	padding-right: 250px;
}

Background images can be added to pretty much any tag. They can be added to divisions, used to create fancy navigation menus, spruce up a list, decorate h tags,…. It’s so exciting!!!!

16. Deleting Browser Default Settings in CSS

Every browser has its own default settings for font size, margins and/or padding around certain elements, etc. Webdesigners should aim to have their sites display well on all kinds of browsers, but these different default settings can easily lead to problems. Sometimes, the differences are subtle and have no effect on the design, but they can also cause a page to totally break in one browser vs. another.

To demonstrate, you could look at THIS PAGE via Browsershots.org. (Just copy and paste ‘this page’ URL, then go to Browsershots and play around).

There is a quick and easy fix so. Start your stylesheet out with this:

* {
margin: 0;
padding: 0;
border: 0;
}

The ‘*’ stands for any and all properties on your page, and this code sets them all to ZERO. Of course, now you’ll have to add your margins, padding, and any borders back in with your CSS in the right places, but usually, you’d have to do that anyway – and this way, it’s much easier to create a cross-browser compatible site.

17. How to Style a Horizontal Navigation Menu with CSS

It’s true: Your navigation items are really a LIST. Bread, Milk, Sugar, Coffee, Home, Contact Us, About, Cheese, Tomatoes, Sitemap. See, it’s a LIST!! And it should be coded and styled like a list. It’s easy.

<ul id="navigation">
<li><a href="#">Home</li>
<li><a href="#">About</li>
<li><a href="#">Stuff</li>
<li><a href="#">Other Stuff</li>
<li><a href="#">Contact Us</li>
</ul>

And it looks like THIS. Note how I’ve given the ul an id. I call it ‘navigation’, but you can call it ‘hamster-parade’ or whatever you chose. However, I’ve long since discovered that using practical and meaningful names for classes, IDs, file names, and images is VERY helpful. So let’s stick with ‘navigation’. The reason for this ID here is that it will allow me to apply a specific style to only the navigation list, while other lists within my site can be styled totally different.

But even so our navigation list is a list, most of the time, we don’t want it to look like one. So first, let’s get rid of the bullet:

ul#navigation {
list-style: none;
}

And to get our list items to line up horizontally, we add:

ul#navigation li {
	display: inline;
	white-space:nowrap;
}

The ‘display: inline;’ line creates the horizontal line. ‘white-space:no-wrap’ prevents our list from wrapping and turning into a 2-line list, which could possible happen when the page is viewed at lower resolutions or the font is increased beyond a certain size in the browser view. And here you go: A Horizontal Navigation List without Bullets. At this point, it’s kind of ugly, but how to dress it up will be a different post.

18. Creating a basic, 2-column, center-aligned fixed width layout with CSS

This type of layout is used a lot, and for good reason. It works.

So let’s start off by looking at the HTML:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="author" content="Andrea Barnett for Killersites">
 
<title>2-Column, Center-aligned Fixed Width Layout with CSS</title>
 
</head>
<body>
 
<div id="header">
<h1>This is the Page Header</h1>
</div>
 
<div id="left-column">
<h2>The Navigation</h2>
</div>
 
<div id="right-column">
<h2>The Main Content</h2>
</div>
 
<div id="footer">
<p>The Page Footer Goes Here</p>
</div>
 
</body>
</html>

Basic Layout Components

I am going to apply a different background color to each division just to make it more obvious where exactly each division is. Colors should be indicated by hex codes – for example #FFFFFF for white or #000000 for black. But for the purpose of this demonstration, I’ll use color names, as it makes things more obvious. So I’m adding the following CSS code to the header:

<style type="text/css">
 
#header {
	background: red;
}
 
#left-column {
	background: yellow;
}
 
#right-column {
	background: teal;
}
 
#footer {
	background: pink;
}
 
</style>

To achieve the fixed width portion of the layout, I’m adding a wrapper division around the entire body html we have so far, like so:

<body>
 
<div id="wrapper">
 
<div id="header">
...
 
</div> <!-- This closes the wrapper division -->
 
</body>

and in the CSS, I’m giving this wrapper division a background color just for demonstration purposes – and a width. The width is based on current trends per W3Schools Browser Trends. According to this information, the vast majority of all surfers views at resolutions of 1280 or higher, so I’ll shoot for 1280px. To allow room for the scroll bar and a bit of the (white) body background to show, I’ll set the width of my wrapper at 1200px. The CSS that actually centers everything is a right and left margin of ‘auto’ to the wrapper:

#wrapper {
	background: silver;
	width: 1200px;
	margin: 0 auto;
}

And now we see THIS. Isn’t it just beautiful? The division is centered by this line

margin: 0 auto;

The ‘0’ tells the browser to display a margin of zero for the top and bottom of the wrapper division (that can be changed if you want a top and/or bottom margin) and to automatically calculate the right and left margin so the division will center. But what about the 2-column thing? I’m getting to that!

So we’ve set our wrapper width at 1200px. That means whatever fits inside, cannot be any larger that those 1200px. So I’ll set my left-column division to 300px and the right-column division to 900px. But that does not yet create the 2-column layout we’re working on. In order to achieve that, I have to get the divisions to line up next to each other, and there are several ways to achieve that. For this example, I’ll float the left-column by adding this CSS

#left-column {
	background: yellow;
	width: 300px;
	float: left;
}
 
#right-column {
	background: teal;
	width: 900px;
	margin-left: 300px;
}

and just to make everything more realistic, I’ll add a bit more content to my html, and now we see THIS – this does NOT look quite right. So what’s happening? That’s a topic for a whole other post, but in a nutshell: A floated division is removed from the actual flow of things – kind of hovering over the floor like a balloon, so not affecting the actual floor space. The non-floated divisions, however, do take up ‘floor space’ and fall in place in their natural order. So the footer division follows the content division, ignoring our entire ‘balloon’. There’s an easy fix, so:

#footer {
	background: pink;
	clear: both;
}

and voilá – ‘clear: both;’ told our footer division to do just that – clear any floated or non-floated divisions and get in line where it belongs.

And here you go – a very basic 2-column, center-aligned fixed width layout with CSS.

As you get rid of the ridiculous background colors and add your own styling – mainly margins and padding to the right and left column – you will probably find that your lay-out breaks. That is because any right and/or left margin and/or padding adds to the total width of your division. Right now, the wrapper is 1200px wide, same as the total of the right (900px) and left (300px) column. But if you add a 10px right/left padding to the right-column, it’s suddenly 920px wide and no longer fits next to the left column. So you have to adjust the total width of right-column to 880px. Because 10px left padding + 10px right padding plus 880px = 900px. Simple math.

19. Styling Headings with CSS

Different browsers have different default styling for headings – the h1, h2, h3, etc. tags. (Default Heading Styling). However, with a little bit of CSS, we can style them any way we like.

If we want to apply certain styles to all our headings – for example margins to create a larger space above the header than between it and the following paragraph, write the CSS like this:

h1, h2, h3, h4, h5 {
	margin-top: 35px;
	margin-bottom: 0;
}

(See the Styled Margins.) Also note that the bottom margin which is set as zero, does NOT have a unit of measure. Zero does not need any unit of measure; zero is zero, whether it’s px, em, percent, whatever.

Maybe we want our headings in a different font than the rest of our page, and with this CSS

h1, h2, h3, h4, h5 {
	margin-top: 35px;
	margin-bottom: 0;
	font-family: Arial, Helvetica, sans-serif;
}

we can achieve that with minimal styling: (See Arial Font Applied to Headings.)

Or we can address individual tags:

h1 {
	color: #FF0000; 
}
h2 {
	background: #FFFF99; 
}
h3 {
	text-align: center;
}
h4 {
	font-style: italic;
}
h5 {
	color: #CCFFFF; 
	background: #000099;
}

And all of the above creates this.

20. Styling Links with CSS

Most browsers will show links by default in blue and visited links in purple. BOOOORING!!! That, and purple just doesn’t look good on some people. (See a boring link without style) But with a little bit of CSS, you can style your links any way you like.

There are several states a link can be in:

  • link – default (so your standard, never-clicked link)
  • visited link
  • focus – when tabbing with the keyboard
  • hover – when the curser moves over the link
  • active – the moment the link is clicked

Love-Hate: Link, Visited, Hover, ActiveWhen you are using CSS to style your links, this exact order has to be maintained, or your styles may not work properly. I am not saying you have to use all the properties, but those that you use must be styled in this very order.

There are a couple ways to help remember this order. The more common one, which does not include ‘focus’, is LoVe – HAte and then there is Lord Vader’s Former Handle Anakin. I’m sure you get the point.

It’s very easy to add some color to our link and its states:

a:link {color: #006600;} (green)
a:visited {color: #FF0000;} (red)
a:focus {color: #9933CC;} (purple)
a:hover {color: #000099;} (blue)
a:active {color: #FF9933;} (orange)

Look at this Link Styling….

Or we can play with background colors and get a bit fancier.

a:link {
	color: #006600;
	background: #CCFF99;
}
a:visited {
	color: #FF0000;
	background: #ff6633;
}
a:focus {
	color: #9933CC;
	background: #ffccff;
}
a:hover {
	color: #000099;
	background: #ccffcc;
}
a:active {
	color: #FF9933;
	background: #ffff00;
}

Check This Out!!

21. CSS Shortcuts

Shortcuts are a good thing. They save time, gas, and make life easier. And who wouldn’t like things easier? Why write:

body {
background-color: #ffffff;
background-image: url(image/picture.jpg);
background-repeat: repeat-x;
background-position: top right;
}

if you could just write:

body {
background: #ffffff url(image/picture.jpg) repeat-x top right;
}

All this:

#example {
border-top-color: #cccccc;
border-top-width: 5px;
border-top-style: dashed;
border-left-color: #cccccc;
border-left-width: 5px;
border-left-style: dashed;
border-bottom-color: #cccccc;
border-bottom-width: 5px;
border-bottom-style: dashed;
border-right-color: #cccccc;
border-right-width: 5px;
border-right-style: dashed;
}

Could be written like this:

#example {
border: #cccccc 5px dashed;
}

Isn’t it beautiful?

But what if you don’t want all sides the same? No problem. These shortcuts work on all kinds of properties. Let’s use the margin for this example:

p {
margin-top: 5px;
margin-right: 10px;
margin-bottom: 15px;
margin-left: 20px;
}

Do take note of the order I have listed these properties in. When you list them out like I did here, the order does NOT matter, but I am using the top-left-bottom-right order for a reason: That’s how CSS is understood by your browser. So instead of all those lines up here, you could write:

p {
margin: 5px 10px 15px 20px;
}

If all 4 sides are the same – let’s go with 10px, just write:

p {
margin: 10px;
}

If your top and bottom are, for example, 20px but your right and left side 40px, you can write:

p {
margin: 20px 40px;
}

And, one last option:

p {
margin: 10px 40px 5px;
}

This would tell your browser to display the top margin as 10px, right and left side as 40px, and bottom as 5px.

In general, it’s a simple principle, and easy to remember – just think clock: noon, 3, 6, and 9 o’clock. Same order. For the longest time, so, I could not remember which sides this 3-dimensional shortcut referred to, until I realized that my head and my bottom are clearly of a different size, but my arms are the same length (well, almost).

22. How to Create a Center Aligned Page with CSS

A website tends to look more balanced when it’s centered on the monitor, instead of clinging to the left side with lots of white space on the right. This looks even worse with increased resolution. And it’s not that folks will use that white space to make notes…..

So to center your page, wrap your content into a container – a ‘wrapper’ of sorts. Like so:

<body>
<div id="wrapper">
<div id="content">
<p>This is where your entire content would go:
- header, navigation, footer, whatever.  
It would likely be in different divisions, but for this demonstration, 
we do not need those details.</p>
</div> (this closes the 'content' division)
 </div> (this closes your 'wrapper' div)
</body>
</html>

And now we use two simple lines in the CSS to move things to the middle:

First, we need to give our wrapper a width:

#wrapper {
      width: 980px;
}

How wide you set this wrapper, of course depends on your design. Instead of pixel, you could use %, or even em, but pixel is probably the better choice.

And here comes the magic wand:

#wrapper {
      width: 980px;
      margin: 0 auto;
}

And voila – a perfectly centered website! What did it is the line:

margin: 0 auto;

It tells the browser to put a margin of zero to the top and bottom of the wrapper division (of course you can adjust that to your liking) and to automatically figure the right and left margins to center the wrapper (that needs to stay ‘auto’ for the centering to work).

P.S. – In the olden – aka pre-IE6 days, this needed to be done by adding a

body {text-align: center;}

and then, to neutralize all that, a

#wrapper {text-align: left;}

But thank goodness, those days are gone. It’s been ok to NOT support anything less than IE6 for a long time now, and even IE6 is about to be extinct.

23. CSS Block and Inline Elements: Part 1

In part one, I will explain how block and inline elements work

Block Level elements:

Most of the tags you will use in HTML (<p>, <div>, etc…) are rendered as block level elements. Blocks span the full width of space available, and skips a line on the top and bottom of the block.

For example (using the <p> tag):

This is a block level element

Notice how there is a break at the beginning and end of the block, and how it uses the full width available.

Inline Level Elements:

There are HTML tags that are rendered as inline elements (<b>, <i>, etc…). These elements do not break the flow and fits wherever it is placed.

For example (using the <b> tag), this is an inline level element. Notice how the element does not affect the flow of the text. It sits right with the text.

In part 2, I will show you how to manipulate elements using the CSS Display property.

24. CSS Font Sizes

In this tip, you will learn how to specify a font’s size with CSS.

Being a practical nerd, I will not waste time talking about all the various methods for declaring font sizes with CSS … instead I will concentrate on the two widely used ways and then briefly explain the differences. First, the two main methods:

  1. By pixel
  2. By em

What is the difference between and EM and a pixel?

Pixels are an absolute measure of a font’s size and an EM is a relative measure – that means the actual pixel size of the font (as they appear on screen) set with EM’s, can fluctuate. This makes using EM’s trickier. So the nerd answer is NOT to use EMs!

Let’s look at a quick EM example anyway:

<div style="font-size:1.2em">

So the above would cause the fonts to be about 20% larger than the baseline font size – thus 1.2em. I am not going to go into all the nerd details about EM’s because I think pixels are the way to go.

Let’s look at a quick pixel example:

<div style="font-size:12px">

25. CSS in Webpages

For some of you, this may sound like a real lame article. But you ought to give it a chance because I don’t write about stuff you’ll never use! I avoid marginal, nerd centric ivory tower blather like a cat avoids water.

I’ve read hundreds (sadly, this is true) of those 2-inch thick nerd books (I don’t get out much) and I can’t stand it when people waste paper on that kind of generally useless stuff. So read on, eager student, and you will be well on your way to building your own killer web sites! 🙂

The wise people who created CSS came up with 3 basic ways for you to use CSS in your web pages:

1. With an external file that you link to in your web page:

<link href="myCSSfile.css" rel="stylesheet" type="text/css">

or using the import method:

<style type="text/css" media="all">
   @import "myCSSfile.css";
</style>

Why use the import method versus the link method when using external style sheets? Use the import method if you want to support really old browsers like Netscape 4.0.

Read the rest of the 3 ways to add CSS code to your web pages.

26. Inserting Images with CSS

This article assumes that you know at least basic HTML; you know what a tag is and how to use simple tags like the <img> or the <p> tag. If this is confusing you, you need to read my tutorial for total beginners on web design – it’s really easy and people seem to like it, so give it go!

This article assumes that you know at least basic HTML; you know what a tag is and how to use simple tags like the <img> or the <p> tag. If this is confusing you, you need to read my tutorial for total beginners on web design – it’s really easy and people seem to like it, so give it go!

Ok, I assume that everyone knows what images are, as we all have seen images on web pages. Images are not technically inserted into a web page (to be nerd precise), rather images are linked to web pages and typically we use the image tag (<img>) to create holding space (or a reference to the image) for the image.

When someone loads a web page (by going to the URL), it is the browser, at that moment, that actually gets the image from the web server and inserts it into the page for you to see – makes sense?

This is different from using a program like MS Word for example, where with Word, when you insert an image into a Word document, the image actually becomes ‘part’ of the actual document. When you save a Word file, all you need to keep track of is that one Word file, and you know the images you inserted will be there when you open it again no matter where you move the file.

Where as with an HTML page, since you are only referencing the images with the image tag, you have to make sure that the images you are linking to always stay in the same spot in relation to the web page. When people mess up that path between the HTML page and the images it is referencing, you get that broken link icon that everyone loves to see. You are seeing that broken link icon because the browser can’t find the image you are referencing in the <img> tag.

Ok, if you didn’t know much about the mechanics of images loading in web pages, now you know too much! Lets move to something practical.

Using CSS to insert images into your web pages

This next part is really easy to understand, easy to use and can be very powerful – triple bonus! With CSS, all block-level and inline elements (tags) can have background images inserted into them. block-level tags are <p> and <div>.

Even though you can insert images into any type of tag (block-level or inline), I think it is better form in most situations to use block-level tags for this sort of thing. But in reality it doesn’t matter if you use block-level tags, or inline tags because you can turn any tag into a block-level tag and vice versa; with this simple CSS code I change any tag to block-level:

display: block;

Or the reverse:

display: inline;

So what? Remember my newsletter where I talked about inserting backgrounds with CSS? In the same way you can insert images in the backgrounds of your web pages, you can do it with any other element. This combined with some extra padding and you have your headline image where you want it.

Take a look at this code where I use this technique:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
   <title>CSS image placement</title>
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
 
   <style type="text/css" media="screen">
   #headline1 {
      background-image: url(images/newsletter_headline1.gif);
      background-repeat: no-repeat;
      background-position: left top;
      padding-top:68px;
      margin-bottom:50px;
   }
   #headline2 {
      background-image: url(images/newsletter_headline2.gif);
      background-repeat: no-repeat;
      background-position: left top;
      padding-top:68px;
   }
</style>
</head>
<body>
   <div id="headline1">Some text … </div>
   <div id="headline2">Some more text .. </div>
</body>
</html>

To keep this example easy to follow, I inserted the CSS code into the web page itself. Typically I would place my CSS code in a separate CSS file and link to it so that I could reuse the CSS code on many pages.

In the above CSS code you will notice that I insert a background image for each ID (headline1 and headline2) and I increase the padding at the top (padding-top:68px) to push down the text to make space for the background images.

This may seem unclear now, so just take a look at the page and then pop open the source code and check it out for yourself. Feel free to take a copy and play with the padding number and see how it changes things. Why did I add 68px to the padding? The image is 68px tall, but I could put any number I like to get the placement I want. Padding does not affect the background image; it only affects the contents inside the tag/element. In this case I used <div> tags.

27. Making Web Pages Printable with CSS

Introduction:

In 2003 I wrote an article on how to use CSS to make web pages printable. I figure that it made sense to include it here … the article:

One of the classic problems with how web pages are designed, is that they are horrible to print. Horrible in the sense that page elements (text, images, etc.) don’t line up and unwanted images and navigation links get printed.

I am as guilty as anyone of creating pages like that, but I am aiming to fix it for your websites and mine. While most other web designers will create separate ‘printable’ pages (big waste of time), we will only be making some simple additions to our pages to make them ‘print friendly’.

Basic ideas:

* People will print your pages typically to be able to read the content, not to see pictures. You need to hide all images from the printer and this is done in the print style sheet. I will explain what the print style sheet is in a moment.
* Navigational elements are not needed in the printed document as well, so all navigational elements should be removed from the printed page.
* Let’s say you designed your pages with a black background with white text. You don’t want peoples printers printing all that black, they won’t be too happy with the price of ink these days! To solve this problem, in our print style sheet we will set the page color to ‘white’ and the text color to ‘black’.

The ‘print style sheet’:

I’ve mentioned the ‘print style sheet’ a few times with no explanation; let’s take care of that now:

CSS today allows you to link to more than one style sheet in your web page.

The simple reason you would want to do this is so that you could have the HTML page ‘change’ its appearance automatically when someone visits your page with a particular type of device. These types of devices can include a typical desktop computer, a PDA (Windows CE device, Palm Pilot, etc.) and a printer among other devices!

It works like this; when you link a style sheet to your HTML page, there is an attribute that you can specify in the CSS link tag that tells the device reading your page if it should use the style sheet specified in the link.

So the wise men and women that came up with the CSS specification, came up with a few ideas for device types that could be specified in the CSS link. For the sake of this short article we are concerned with only two of them:

1: ‘print’

2. ‘screen’

Here’s a sample pair of CSS links that point to different style sheets, one for the printer to use and the other for a normal PC monitor to use …

You can check out the rest of the tutorial on making web page printable with CSS on Killersites.com.

Making Web Pages Printable Using CSS

One of the classic problems with websites, is that they don’t print very well. That means that page elements (text, images, etc.) don’t line up, unwanted images and navigation links get printed – you basically have very little control, in terms of how your web pages look when they are printed.

What is the solution!!

The ‘old-school’ way, was to create separate ‘printable’ pages – this is a big waste of time! Instead, with the power of CSS, you will only need to make a few simple additions to your web pages and they will be printer friendly.

Basic Concepts

  • People will print your pages typically to be able to read the content, not to see pictures. You need to hide all images from the printer and this is done in the print style sheet. I will explain what the print style sheet is in a moment.
  • Navigational elements are not needed in the printed document as well, so all navigational elements should be removed from the printed page.
  • Let’s say you designed your pages with a black background with white text. You don’t want peoples printers printing all that black, they won’t be too happy with the price of ink these days! To solve this problem, in our print style sheet we will set the page color to ‘white’ and the text color to ‘black’.

The Print Style Sheet

I’ve mentioned the ‘print style sheet’ a few times with no explanation; let’s take care of that now. CSS today allows you to link to more than one style sheet in your web page.

The simple reason you would want to do this, is so that you could have the HTML page ‘change’ its appearance automatically when someone visits your page with a particular type of device. These types of devices can include typical desktop computers, iPhones, Android phones, iPads and printers … among other devices!

It works like this; when you link a style sheet to your HTML page, there is an attribute that you can specify in the CSS link tag that tells the device reading your page if it should use the style sheet specified in the link.

So the wise men and women that came up with the CSS specification, came up with a few ideas for device types that could be specified in the CSS link. For the sake of this short article we are concerned with only two of them:

  1. screen
  2. print

Here’s a sample pair of CSS links that point to different style sheets, one for the printer to use and the other for a normal PC monitor to use:

<link href="CSS/webdesignersHanbook_Print.css" 
rel="stylesheet" type="text/css" media="print"> 
 
<link href="CSS/webdesignersHanbook_1.css" 
rel="stylesheet" type="text/css" media="screen">

You can see that these CSS links are actually taken from the Handbook on Killersites.com. What you’re looking for in the link is this text:

media="print"

… and:

media="screen"

The first (‘media=”print”‘) points to the style sheet that has been set up for printing while the other (media=”screen”) is set up for normal PC monitors. Nowadays most browsers know that if someone tries to print the page the style marked with: ‘media=”print”‘ should be used.

So now we know how to tell the browser which style sheet to use when printing the HTML page, so what is different in the print style sheet that makes this work?

There are all kinds of things you can do, but the easiest is just to wrap HTML and images (you don’t want printed) with div tags and give all those div tags an ID of a style that is set to:

display: none

What?!

Ok, the best way to understand this, is to see it work. Create a simple HTML page and create a new style sheet and call it: print.css. In that style sheet you insert this code:

 .noPrint { 
          display: none; 
          } 

Now in your HTML pages, just wrap DIVs around elements you don’t want printed:

 <div class='noPrint'> 
 
 <p>Text that I don't want printed.</p> 
 
 </div> 

 … Don’t forget to include your CSS links in the of your HTML page! So basically, any elements inside the DIVs that have the class ‘noPrint’ applied to them, won’t print.

Let’s keep moving …

Another thing you should do is make all you text black and your pages white:

    body { 
 
          font-family: Georgia, "Times New Roman", Times, serif;  
 
          font-size: 14px;  
 
          color: #000000;  
 
          background-color: #FFFFFF;  
         } 

Create a Print Button

To close off this tutorial, here is a simple way to create ‘print’ button on your page using just a tiny wee bit of JavaScript:

<a href="#" onClick=" window.print(); return false">Print this page!</a>

Closing Comments

This quick little article is based on an article I wrote in 2003! I’ve made a few minor updates to it … since a few things have changed since then. We should be all good. If you have questions – feel free!

28. Learning Advanced CSS Selectors

There many ways you can apply CSS to HTML tags – I am talking about the many CSS selectors. The basic selectors are:

  • class selectors
  • ID selectors
  • tag selectors

I assume you know what selectors are, because you’ve either done my basic CSS tutorial (found on this site,) or you’ve done my beginners web design video course, found on Webmentor.org. So I won’t get into the details in this article. Instead, I just want to quickly talk about the advanced CSS selectors you have to choose from – for instance:

  • pseudo selectors
  • attribute selectors
  • ::first-child selectors

.. And the list goes on. The point is that you should not get too concerned about learning all of them, because you will rarely use most of them!





Comments