Tips on reducing wrapper DIVs?

I like to keep my marker up clean.

However, for some designs, using a wrapper DIVs for elements is unavoidable.

Are there any tips or techniques to avoid this?

I know you can use the before and after psuedo CSS elements to insert (presentational-only) objects without creating extra mark up. But it is there a similar technique for creating wrapper DIVs?

I know there is jQuery command for creating wrapper DIVs, but obviously that creates a problem if the user is viewing the page and has Java Script disabled.

Hi,

It all depends on the job in hand and the structure of the page.:slight_smile:

You only need wrapper divs when you want to group elements logically and to divide your page into usable structures. There are times when you need extra divs for presenatational elements and backgrounds but eventually css3 will cut down on that with multiple backgrounds etc.

Most times though I see authors adding divs when none are needed.

e.g. I see this structure almost daily.


<div id="header">
    <h1>Header</h1>
</div>
<div id="nav">
    <ul>
        <li><a href="#">menu</a></li>
        <li><a href="#">menu</a></li>
        <li><a href="#">menu</a></li>
        <li><a href="#">menu</a></li>
        <li><a href="#">menu</a></li>
        <li><a href="#">menu</a></li>
    </ul>
</div>

The header only contains the h1 yer why is the div wrapped around it?

Worse still the navigation has a perfectly good wrapper in the ul element yet it sits there wasted because the author placed an unnecessary div around it. I see this many times daily and it’s a complete waste (and now even worse in html5 with the nav element tacked onto the above structure as well).

Whenever you add a wrapper or a div to the page you must ask yourself what it is for? If it’s not in place for a very good reason then it shouldn’t be there.

Just use the most semantic element for the content you are describing and you won’t go far wrong.

As to generated content then that’s a presentational issue and has nothing to do with structure at all and shouldn’t be used for real content. The same goes for javascript and it should be used to enhance the experience and not replace real content or structure.

Hi Thanks for the reply.

In my case, I am creating a magazine style grid layout, where a single article is made up of sub-units, which create groups of images or groups of paragraphs.

From a semantic view point, there is no reason for the sub units to be in separate wrapper DIVs, as they are all part of the same section. But I need the groups of images and/or paragraphs to be in wrapper DIVs to create the design.

It’s too bad there isn’t a CSS:wrap psudo element!

If you have groups of image then they probably should be in a lists anyway unless you meant something else.

I’d need to see an example of the code and the desired layout to see if there was a better way to do it. Sometimes authors add extra div wrappers just to create extra padding and margin around some elements when they could have effected the same change on the individual elements themselves instead.

It does all depend on what’s required of course and sometimes you do need extra divs to provide the right structure.

It may also be that is actually more semantic to have your subsections contained in parent divs as then all subsections can be identified by their structure form the main group so the semantics are in fact correct.

As long as you are thinking logically and only adding elements when required then don’t worry too much about the odd extra div.

Remember also that you can use the BODY element as a perfectly good wrapper. You can add your background colours or images to the HTML element and then use BODY as a wrapper for the content. That way you can actually avoid using DIV altogether if your page is relatively simple:

<body>
  <h1>header</h1>
  <ul>nav</ul>
  <h2>sub-heading</h2>
  <p>content</p>
  <p>content</p>
  <h2>sub-heading</h2>
  <p>content</p>
</body>

Obviously that’s not always going to be possible if you need lots of columns or other stuff, but for relatively simple pages there is no need for any wrapping DIVs at all.

Thanks for the replies.

Some of the layouts I am producing are like this:


I think all the units of headings and paragraphs would have to be wrapped in DIVs in order to make the grid.

I guess I could use a list or a definition list, but I think it could end up being equally as untidy!

Obviously you will need some divs but I’d do the middle section roughly like this attachment.

I don’t see a need for each heading and paragraph to be in a div as they are pretty uniform.

I disagree with the ideas of the p and img for the two decorational images… except that maybe the p could be an empty space-creating box.

And the img in such a grid setup would be difficult. Why not as a bg of the large main white container?

For the rest, that’s how I’d do it (like Paul’s). You do need something to wrap each chunk of information, and so yeah since that’s mostly only for styling reasons, it would be nice to have a css-created wrapping element instead of a markup div.

Yes background images would be better but I usually find that clients rotate these types of images and want content to adjust accordingly so I usually allow them to be in the foreground and then nothing else needs to be changed if they change size etc.

The image on the right of the page would have just been floated out of the p tag and the image in the left column could have been inside the exiting p element I suppose (swings and round-abouts).

The images do only look decorative though so should really be in the background as you say.:slight_smile:

Yes background images would be better but I usually find that clients rotate these types of images and want content to adjust accordingly so I usually allow them to be in the foreground and then nothing else needs to be changed if they change size etc.

Hm, true.

It’s hard to have good semantic code when we also expect non-professionals to be content authors.

To be brutally frank (am I ever anything but) those are what I like to call “non-viable for the web” layouts – it REEKS of being designed for print, not the web.

UNFORTUNATELY thanks to the varying layouts on every page you’re going to be blowing tons of CSS and from all the massive images wasting tons of bandwidth – again, time to kick the PSD jockey where it hurts and explain that the web is NOT print.

That said, your looking at a few extra div for the formatting, but on the whole there’s no reason you can’t have simple semantic markup for that as long as you practice separation of presentation from content.

I mean, if I was to try to turn the first image you have into a layout, the markup would probably go something like this (+/- 5%)


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html
	xmlns="http://www.w3.org/1999/xhtml"
	lang="en"
	xml:lang="en"
><head>

<meta
	http-equiv="Content-Type"
	content="text/html; charset=utf-8"
/>

<meta
	http-equiv="Content-Language"
	content="en"
/>

<link
	type="text/css"
	rel="stylesheet"
	href="screen.css"
	media="screen,projection,tv"
/>

<title>
	Elite Energy
</title>

</head><body>

<div id="pageWrapper">

	<h1>
		<span>
			Elite Energy
			<span>For Business</span>
		</span>
		<small>Providing Green Energy Solutions</small>
		<b><!-- image replacement --></b>
	</h1>
	
	<a href="#" class="topLink">View Website for Home Customers</a>
	
	<ul id="mainMenu">
		<li class="home"><a href="#">Home<span></span></a></li>
		<li><a href="#">Solar Energy</a></li>
		<li><a href="#">Solar Heating</a></li>
		<li><a href="#">Case Studies</a></li>
		<li><a href="#">FREE Consultation</a></li>
		<li><a href="#">Contact Us</a></li>
	</ul>
	
	<div id="stupidBannerCrapIdProbablyDelete"></div>
	
	<ul id="tabbedMenu">
		<li><a href="#">The Solar Package</a></li>
		<li><a href="#">Instant Benefits</a></li>
		<li><a href="#">Minimal Sun Needed</a></li>
	</ul>
	
	<h2>How will my business benefit from an Elite Energy Installation</h2>
	<p class="standout">
		Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.
	</p>
	
	<div class="leadingBar handout">
		<h2>Get Paid for Using Electricity with FiT</h2>
		<p>
			Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
		</p>
	<!-- .leadingBar --></div>
	
	<div class="trailingSection">
		<div class="stacksOfCash">
			<h2>Get Paid for Selling Electricity with Export Tariff</h2>
			<p>
				Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
			</p>
		<!-- .stacksOfCash --></div>
		
		<h2>Tax Free Wrapper for Profits</h2>
		<p>
			Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
		</p>
	<!-- .trailingSection --></div>
	
	<div class="columnWrapper">
		
		<div class="subSection">
			<h2>Slash Operating Costs</h2>
			<p>
				Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
			</p>
		<!-- .subSection --></div>
		
		<div class="subSection">
			<h2>Slash Operating Costs</h2>
			<p>
				Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
			</p>
		<!-- .subSection --></div>
		
		<div class="subSection">
			<h2>Slash Operating Costs</h2>
			<p>
				Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
			</p>
		<!-- .subSection --></div>
		
	<!-- .columnWrapper --></div>	
		
<!-- #pageWrapper --></div>

<div id="footer">

	<div class="elite">
		Elite Energy 
		<small>Providing Green Energy Solutions</small>
	<!-- .elite --></div>
	
	<div class="linkList">
		<h2>For Home</h2>
		<ul>
			<li><a href="#">Solar Electricity</a></li>
			<li><a href="#">Solar Heating</a></li>
			<li><a href="#">Case Studies</a></li>
		</ul>
	<!-- .linkList --></div>
	
	<div class="linkList">
		<h2>For Business</h2>
		<ul>
			<li><a href="#">Solar Electricity</a></li>
			<li><a href="#">Solar Heating</a></li>
			<li><a href="#">L.E.D. Lighting</a></li>
			<li><a href="#">Case Studies</a></li>
		</ul>
	<!-- .linkList --></div>
	
	<ul class="standalones">
		<li><a href="#">Free Consultation</a></li>
		<li><a href="#">Contact Us</a></li>
	</ul>
	
<!-- #footer --></div>

</body></html>

Which yes, has a lot of div, but they’re all necessary and at 6k before links, there’s no reason for it to break the 10k mark once the proper content and links are filled in. It’s laughably small even with the comments to clearly show what’s being closed and the full indentation. (part of why I say comment and white-space stripping for deployment is usually just used to cover up bad/flawed code)

Though I’ve said it a billion times – if you have some goofy picture slapped together by a PSD jockey before you have semantic markup, your ENTIRE approach to building a website is backwards… Semantic markup of the content, layout in CSS, THEN you boot up the paint program to hang graphics on it. Slapping together a picture before you even have a logical document structure is just putting the cart before the horse – and leads you into the trap of “but I can do it in photoshop”.

Seriously, whoever came up with this “draw a pretty picture that has NOTHING to do with a working website” nonsense meets me in a dark alleyway, bad things will happen.

In defense of the PSD jockey, its the CLIENT that ask the web to be print. 17of20 clients actual ASK Ads and GDs VERBATIM to do this. So it’s difficult to avoid , even if you do know better. I even made the mistake once to show a client clean code of the sight I build for them and a couple of other similar ( semantic-content wise) sites… they went from loving the site to being bitter at the idea that similar semantic-content leads to similar semantic-structure. I believe this is the clash of humanity and tech and can’t really be helped… but I dont like the finger pointing.

Ok, that rant over. The truth is you need to optimize your code on a per case basis.

As it has been said before if you only have a simple flat bg, you may be able to put it in the HTML tag and use the BODY as a wrapper… but what if you had 3 fades? You also have to consider what happens when the window is shrunk to less than the width of the page… do you have a sticky footer? etc etc…

The one tip I can give is to begin with content structure… Some times , you will actually need more tags that you thought… which can later serve as natural hooks. For example… in you cant put inputs and labels directly within a form tag, they need to be contained in block level elements.

Once you have the proper semantic structure built , you can group for layout ( floating, and AP)

after that consider what semantically neutral tags will be needed as image, positioning or replacement hooks, only if you cant do it within the barebone semantic structure… and DONT feel guilty about…

The true trick at that point is to remember that CSS design is not concrete or linear.

for example: you can border an element ( lets say, for the sake of the example, on the top and bottom) by giving it border-top:, border-bottom: … you can also achive the same visual effect by giving adjacent elements border-top:, border-bottom:… each technique has a different effect on the behavior floats, and margin. Normally people (non-designers, designers, print-designers, and some web-designers) apply divide-and-conquer techniques … where they feel that IF they can get the menu-layout use solved THEN the header issue THEN the footer… they can eventually arrive at their desired layout with reasonably clean code…

but the thing is in web the design everything affects everything else… so you need to have a holistic and non-purist mindset through the design process …

In defense of the PSD jockey, its the CLIENT that ask the web to be print. 17of20 clients actual ASK Ads and GDs VERBATIM to do this.

People wanted fins on cars too. Doesn’t mean it wasn’t stupid.

This makes me glad I’m not a freelancer, because it would mean my knowledge would be pointless, ignored, and wasted.

This points out some interesting differences between merchants and professionals. Of course, it’s also advice only large artsy media bureaus with ginormous rich clients can follow, but it’s a cute idea. Most of us are stuck on the merchant level, if we want to keep eating and stuff.

That’s a good read, reminds me of “of wolves, sheep and sheepdogs” in it’s view in the difference between clients vs. customers – and Professionals vs. Merchants.

“But what if you have a capacity for violence and a love of your fellow man? Well, then you’re a sheepdog.”

That’s what I was trying to say, Somme and many people still drool when you mention them with fins on cars, btw…

I find that there is ADDED strain on freelancers, as clients believe them to be a dime a dozen ( “You have such an ego, a guy in India told me he WOULD do MY iPhone site IN FLASH fro 1/10th the price!!!”) …lol.

What i am saying it begins way before the first pixel in PS or teh first required or superfluous tag is coded. I will admit that the following anecdote is an example of my own stupidity… A few years back I was doing freelance copy-writing and was brought in to do a couple of brochures for a local cultural organization. Seemed easy as pie, so I figured I could give a competitive quote , have a nice new sample piece for my portfolio, and even make a nice profit. Am not gonna go into the mess of copy revisions all of which too a lot of impact away from the copy I was being paid to come up with… but I will mention that it nearly became breaker for them when the DEMANDED I put their URL in the brochure. I should rephrase that, I googled their URL, found that there was no such address, asked about it, found out that they had not even THOUGHT about purchasing a domain name, but that they need to have my copy ready so that they could have some design a brochure to flow it so that it woudl be ready in 3 weeks to be handed out at some festival!!! Yup. In the end I paid out of pocked to purchase TWO ( they then couldnt decide on".com" or “.org”… a story in an of itself) domain names… so that I could have the URL I needed so that I could finish the brochure so that they felt they could pay me… Incidentally, since a URL, in NOT a site… (“but we PAID for a site”) … I put a “brick” ( a JPG or a layout I did in Quark)…and a link to a WMV because they INSISTED the sight play an Italian song… Did I mention I was hired as a copywriter to write two FESTIVAL SPECIFIC brochures?

I wish I could say this is a fluke and not the norm of client behavior , but it really isn’t. I would also like to say I am PICKY in selecting clients, but the truth is that client’s can be just as devious as some merchants. Then there is of course the flow of clients… I have bills to pay. So while I pride myself in doing a good work; I work for money not for ideals. I will advice the client on best practices… but that all any professional OR merchant can do, lest you be branded a “primma-donna”. Reading that article, it seems that a professional is a well learned merchant who got lucky with the client he or she was able to obtain.

and many people still drool when you mention them with fins on cars, btw…

Me included actually lawlz. I’m a sucker for chrome and big square bodies : )

What i am saying it begins way before the first pixel in PS or teh first required or superfluous tag is coded. I will admit that the following anecdote is an example of my own stupidity…

Those people should have gotten what they paid for. I wouldn’t have bought any domain names. Some people don’t know what the internets is, even if they heard a rumours on it.

Going back to the original questions, the best way to avoid extra divs is to code the content semantically first, without any reference to the way the site actually looks. Just get the content down. Then use that content to attach relevant styling. If you really absolutely cannot find any way to get the visuals you need using the semantic HTML you already have, then and only then add divs to attach styling.

In my experience, most extraneous divs come from approaching the coding from the wrong direction.

In other words, basically what deathshadow said. :slight_smile:

@ STomme: that’s the problem they wouldn’t have paid for anything had I not done what I did. In other words, I would have neither been a professional nor a merchant.

@Pat:

HTML is about content. so yes. begin with a pattern of the content and crate the MOST bare bones , SEMANTICALLY CORECT, hierarchic structure. You will find that some times this actually adds tags by necessity, especially with forms and blockquotes.

After adding divs for styling you may find that , looking at which dibs are adjacent, you MAY or may not be able to pair down the #divs by reconsidering your bg slices, borders etc… based on which tags are adjacent to each other.

CSS3, and even 2.1 is not supported by all browsers, so how far back you want to provide support for. ( this gets into deeper into the concept of "progressive enhancement tho)

WORD. That’s it in a nutshell!

Not doing the above is the most common reason for excess DIV – if you look at the code I posted MOST coders when writing their markup would have a div around both the menu and the h1, and individual div’s around BOTH the h1 (or a div instead of the h1) and the menu – for NOTHING. 99.99% of layouts don’t need those extra elements. Also see why I’m NOT a big fan of HTML 5 – with it’s “NAV” and “HEADER” tags serving no good purpose other than making an excuse for the people who use those extra DIV to continue doing so. Basically again, the same people who vomit up HTML 3.2 and slap a tranny doctype on it (or worse, the HTML 5 lip service) to call it modern code.

Seriously 99% of the time I see <div id=“header”> or <div id=“nav”> I feel the urge to backhand someone. We’ve got perfectly good numbered heading tags, we’ve got perfectly good semantic wrappers like UL – both are perfectly good block-level containers – what do you need the extra wrapper for?

[QUOTE}I disagree with the ideas of the p and img for the two decorational images… except that maybe the p could be an empty space-creating box.[/QUOTE]

Paul could get rid of the p image by simply putting it in the padding of the h3, which can be targeted in a variety of ways #pounds{} ( <h3 id=“pounds”) or if you know there are only two h3 in the container … p+h3{}