Friday, February 6, 2009

DIV and SPAN in CSS

The <span> and <div> tags were introduced later in the HTML game that are very useful when dealing with Cascading Style Sheets. People tend to use them in similar fashion, but they serve different purposes.

<Div>

The <div> tag defines logical divisions in your Web page. In terms of layout, the <div> tag does only one thing, it determines the alignment of that section of your page.

<div> also gives you the chance to define the style of whole sections of HTML. You could define a section of your page as a call out and give that section a different style from the surrounding text.

But that's not all it does! The <div> tag gives you the ability to name certain sections of your documents so that you can affect them with style sheets or Dynamic HTML.

One thing to keep in mind when using the <div> tag is that it breaks paragraphs. It acts as a paragraph end/beginning, and while you can have paragraphs within a <div> you can't have a <div> inside a paragraph.

The primary attributes of the <div> tag are:

align (left|center|right|justify)
style
name

Even if you don't use style sheets or DHTML, you should get into the habit of using the <div> tag. This will give you more flexibility when more XML parsers become available. Also, you can use the NAME attribute to name your sections so that your Web pages are well formed.

Because the <center> tag has been deprecated in HTML 4.0, it is a good idea to start using <div> align="center" to center your text and images. You can also use the text-align: center style tag.

More About the <div> Tag

<span>

The <span> tag has very similar properties to the <div> tag, in that it affects the style of the text it encloses. Items in the <span> can be aligned or given specific style attributes.

The primary difference between the <span> and <div> tags is that <span> doesn't do any formatting of it's own. The <div> tag acts as a paragraph break, because it is defining a logical division in the document. The <span> tag simply tells the browser to apply the style and align rules to whatever is within the <span>.

The primary attributes of the <span> tag are:

align (left|center|right|justify)
style

Use <span> when you want to change the style of elements without naming them in a separate division within the document. For example, if you had a Level 3 Heading (<h3>) that you wanted the second word to be red, you could surround that word with <<span> style="color : #ff0000;">2ndWord</<span>> and it would still be a part of the <h3> tag .

No comments: