Pages

Labels

Powered by Blogger.
Thursday, August 30, 2012

Divs and spans


One element that can help add structure to a document is the  div element. Many people mistakenly believe that a div element has no semantic meaning. However, div actually stands for division and provides a way of dividing a document  into meaningful areas. So by wrapping your main content area in a div and giving it a class of content, you are adding structure and meaning to your document.

To keep unnecessary markup to a minimum, you should only use a  div element if there is no existing element that will do the job. For instance, if you are using a list for your main navigation, there is no need to wrap it in a div.


<div class="nav">
  <ul>
    <li><a href="/home/">Home</a></li>
    <li><a href="/about/">About Us</a></li>
    <li><a href="/contact/">Contact</a></li>
  </ul>
</div>

You can remove the div entirely and simply apply your class to the list instead:

<ul class="nav">
    <li><a href="/home/">Home</a></li>
    <li><a href="/about/">About Us</a></li>
    <li><a href="/contact/">Contact</a></li>
</ul>

Using too many divs is often described as divitus and is usually a sign that your code is poorly structured and overly complicated. Some people new to CSS will try to replicate their old table structure using  divs. But this is just swapping one set of extraneous tags for another. Instead, divs should be used to group related items based on their meaning or function rather than their presentation or layout.

Whereas divs can be used to group block-level elements, spans can be used to group or identify inline elements:

<h2>Andy wins an Oscar for his cameo in Iron Man </h2>
  <p>Published on <span class="date">February 22nd, 2009</span>
by <span class="author">Harry Knowles</span></p>

Although the goal is to keep your code as lean and mean(ingful) as possible, sometimes you cannot avoid adding an extra nonsemantic  div or span to get the page to display the way you want. If this is the case, don’t fret too much over it. We live in a transitional period, and CSS 3 will give us much greater control of our documents. In the meantime, real-world needs often have to come before theory. The trick is knowing when you have to make a compromise and if you are doing it for the right reasons.

0 Comments: