How Semantic Markup Helps Server-side Developers Write Reusable Code

helpnote-code-teaserIf you spend most of your coding time working directly with the browser, you probably already know how much easier maintenance, testing, and rendering consistency all are when your markup is well-structured and semantic. The importance of separating content and presentation is not lost on you. Moreover, you know how to accomplish that separation well.

If only you could write every single line of code in your next project, you’re certain it would be the cleanest, most maintainable website on the Internet! But websites are rarely the sole products of front-end developers, and in any project that involves a lot of programmatic heavy-lifting it can be a struggle to instill an appreciation for the benefits of a quality front-end codebase on even the most quality-conscious server-side programmers. Too often, what at first seems a minor instance of HTML semantics actually involves quite a number of implications beyond what’s evident to most people (including management and operations departments) in most projects.

Recently, a colleague of mine (a very talented PHP developer), asked a fantastic question about just such a situation. In our project, we wanted to create a line break before the anchor text of a link appearing in notes, which would be rendered differently across the site. My solution was HTML that looked similar to this:

<div class="help-note"><p>
    <span>Can you add a picture to the page about</span>
    <a href="..." title="Help us improve the article about 'Altocumulus clouds'">Altocumulus clouds</a>?
</p></div>

and CSS like this:

.help-note span { display: block; }

My colleague wanted to know why I chose to use a span with an extra CSS rule to accomplish the line break in our artist’s design. Wouldn’t it be more natural, he reasoned, if we just used a div? That way, we could forgo adding CSS at all. Besides, aren’t div elements the same as span elements, except with display: block applied by default?

This is a great question with which to illustrate the interconnectedness that markup has throughout many parts of a website’s codebase. Let’s take a look at some of these implications.

Although practically speaking div and span elements are both intended to be meaningless, there is a subtle difference. This is not only in that the browser’s default styling of these elements is different but also, and arguably more importantly, the implications of logical grouping on a contextual basis.

The W3C says:

The div and span elements, in conjunction with the id and class attributes, offer a generic mechanism for adding structure to documents. These elements define content to be inline (span) or block-level (div) but impose no other presentational idioms on the content. Thus, authors may use these elements in conjunction with style sheets, the lang attribute, etc., to tailor HTML to their own needs and tastes.

At first blush these may seem to be the same, but take a closer look at the wording: these elements define content to be inline (span) or block-level (div).

In other words, the content itself suggests the appropriate element. Since the entire help note is logically a single sentence and is only intended to be split up onto multiple lines when styling is applied (and presumably not in, say, a text-only representation of the content since that would be weird for sentence structure), then a span element is the only one of these two that’s appropriate. movie downloads

Using a span also has technical benefits. For example, assume our users like HelpNotes so much that we decide to use them in more places. We create a class, HelpNote, which has only one output method, with a signature like this:

/**
  * Produces appropriate output of a note for help regardless of display context.
  */
public static function renderHelpNote( Object $title )

This function is what back-end developers can use to output a HelpNote no matter where they call it from. So regardless of whether we use a HelpNote in a multi-part email or web page (for example), in PHP we can just say renderHelpNote( $title ) and be done with the call. This would be useful in, say, a loop or a template system.

Now the question becomes, should the help note sentence use a span or a div? If we use a div, then we know that to create a list-item version of a help note, we have to add logic to the renderHelpNote function in order to omit the div, or to restyle the div as an inline-level element. If we use a span, however, then we’re not only sticking to the sentence structure, but we’re also remaining flexible by adhering to the notion of progressive enhancement, by styling only the most specific cases and letting the more general, low-fidelity designs go unstyled.

Admittedly, this is the sort of precision and obsessive correctness that may be annoying or even senseless to a person unaware of the subtleties. However, I think that’s all the more reason to promote a proper separation of concerns.

As a front-end developer, it’s unimportant to me how the list of help notes is ordered; I simply trust that there’ll be a list and that my colleague will have sorted it in the order he intended. Similarly, I don’t want to force my colleagues to care whether or not the line break will look right; I just want them to output the code and let me handle the display. The result with a span is more than just cleaner front-end code, it’s also simpler, more reusable server-side output logic.

To me, it often feels like there’s a huge culture clash between back-end developers and front-end developers. The choices one group makes can seem crazy to the other. However, more often than not, just a little cross-functional education can go a long way towards writing code that’s better for us all. So ask questions, because techniques that help your colleagues are likely to help you, too.

Update: I love how scrutinous everyone who’s been commenting on this post is! :) Some good points have been made, and some points of clarifications asked for, so I’ve tried to address these in the comments. Specifically, for instance, here’s why this example precludes the use of just styling the <a> element.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Jason

    To me, it’s not clear what the argument is here. The difference between DIV and SPAN is very clear. Using styled SPANs as block elements or styled DIVs as inline elements is feasible but why do you go for SPANs instead of DIVs? Why not use inline styled DIVs to be flexible in the same way? For me this kind of flexibility actually makes redundant the entire structuring logic. Why not use SPANs then everywhere? Different elements have different default behavior in order to be used accordingly. In the same way, you could build a UL LI like behavior entirely with SPANs. You mention that the entire help note is logically a single sentence. What if suddenly were 2 sentences?

  • http://www.sitepoint.com/articlelist/537/ Meitar

    Jason, what I’m trying (and maybe struggling) to get at is that the value in using a SPAN over a DIV, in this example, is most apparent at the next use of the same output. If we subscribe to the idea that front-end techniques should be built by progressively adding layers of behavior one atop of another, then we can see benefits of doing so for back-end code as well as front-end code. In this case, when the back-end developer—who typically just wants to “spit out the HTML” and be done with it—is asked to re-use the same component (a “HelpNote”) in some other part of the system, using a SPAN ensures that the markup he produces in this new place is more likely to be appropriately semantic and less likely to need refactoring.

  • nicksmith

    Hi, Although I agree with the sentiment, I’m not sure if you’re confusing the issue with your example. Is there some other use for this code that you’ve not explained? Is the SPAN a hook for some style requirement we’ve not seen? At the moment you already have a tag (the HREF) that you can apply style to. Why not add a ‘clear:both’ to that? This would give you the line break that you require. You can even tell it to ‘display:block’. In fact, the SPAN element you’ve added is purely for visual style and goes completely against the concept of separating content from style (since that’s your purpose for including it). Also, on some screen readers (OK, I’ve only tested Mac VoiceOver) wrapping text in a SPAN element adds a pause in the sentence, not a major issue but something to be avoided if possible. In a world where DIVs and SPANs are still (wrongly) used in preference of more semantic code like P, UL, Q and the like – I worry that you’re confusing matters. It’s always best to: start with the semantic code > add style to that > then add hooks (extra SPANs and DIVs) as absolutely necessary with a light-touch use of CLASS and ID names. Then you’ll have reusable code. I hope this helps.

  • xNephilimx

    I kinda get the argument, but don’t see the real benefit. And, as a back-end and front-end developer, I think server side code, should avoid printing html code as much as possible. If a function must output code then it is wiser to use a template (don’t misunderstand me, I’m not saying using a template system, I hate those).

  • Good Ol Joe

    Actually if someone produced a
    RFC-for-Dummies(TM) or Spec-For-Dummies(TM)
    for many of the internet standards docs and W3C recommendations, we could ask people to Read The Fine Manual before claiming to know HTML.
    I know treating HTML as a language to learn takes all the fun out of it – but somewhere, when you turn from hobby to serious desing/development, a Dummies series makes life much easier.

    My ideal first page intro to such a document would be something like this:
    “This element is meant for this situation.
    Respect the wisdom of the spec writers.
    Please don’t Perl-ify HTML into tag soup.”

    Nice article.
    I also believe that Sitepoint’s various books might already have addressed these issues.

  • Rob Miracle

    I think the point is that span implies inline, div implies block and though you can change them if you were just reading the code without the CSS handy you would infer that the span tag was meant to be non-breaking.

  • kingkool68

    This whole SPAN vs DIV point is moot. You can just do .help-note a { display: block; } and now there is no need for a span tag.

  • Newton

    @Meitar good article and I think it’s invaluable to have software engineers and developers understand the semantics of the web that user interface engineers use everyday. However, I don’t necessarily agree with your use of semantics here and was wondering if you could clarify somethings.
    Why did you even bother adding the <span> in the first place. Seeing as how it’s a one sentence word, couldn’t you have just added {display: block} on the <a>. Thus eliminating an extra element and increasing the speed.And depending on the way this sentence should read when CSS is turned off, you could theoretically just add a <br /> before the anchor tag and eliminate out the CSS and extra element.
    Your thoughts?

  • stacye

    I understand the article, but I don’t understand why you are choosing between span or div? Why not just style .help-note p and .help-note a? What is the point in using extra markup when you don’t have to?

  • Justen

    I hear you. I came into backend development by way of semantic design and never cease to be amazed at the disaster that backend code often makes of frontend markup. Witness the plethora of templating systems wherein the bulk of the system is angled at allowing a designer to control the markup in order to engineer one or another pre-determined and abusive layout; why not use semantic markup and let the designer handle the presentation in CSS with a minimum of fuss? Think of all the work hours wasted on producing all these markup options and the necessary code to support them when often the problem can be reduced to a couple of semantic tags and a decent stylesheet.

  • KamKam

    I agree with nicksmith, kingkool68 and newton. I had to re-read this article 3 times to try and understand what you were trying to achieve, and it still makes no sense. Your adding a span tag for no reason, you want a line break, you can already do that with the anchor tag. You wanna style the text different from the link, you can still do that. Adding the span has achieved nothing extra, and no extra semantical meaning that “this whole thing is meant to be inline together by the way”. The screen reader disagrees with this also!

    I am a back end coder also heavily involved in the front end. It annoys me when people write bad CSS. And I appreciate how much easier life is with good CSS. But your example is very poor!

    I remember “back in the good old days” when everything was done using tables. Typically writing out menus in a loop you would construct your HTML and then “chop off” the last 4 characters of the string at the end of the loop, cos that was the opening <tr> for the next element. One of the first tricks I learnt was to use <ul> and <li> for these. That made life a million times easier and cleaner, both front end and back!

  • http://www.sitepoint.com/articlelist/537/ Meitar

    nicksmith, kingkool68, Newton: Sadly, it’s not quite that simple. Although it looks as though simply using display: block; on the A element is enough, that creates one-too-many anonymous CSS boxes because then the punctuation (the question mark at the end of the sentence) would also be on its own line, resulting in three lines of text, not two.

    Also, on some screen readers (OK, I’ve only tested Mac VoiceOver) wrapping text in a SPAN element adds a pause in the sentence, not a major issue but something to be avoided if possible.

    That’s an excellent point, nicksmith, and actually a wonderful example of what I’m talking about in this post.

    It doesn’t make sense, to me, for a SPAN to cause a pause in a sentence, but it does make sense to me for a DIV to do so. This highlights precisely the same kind of “logical grouping” differences between the two elements that encourage server-side and, in this case, application developers, to be mindful of when they consider Web rendering.

  • http://www.tyssendesign.com.au Tyssen

    kingkool68 and Newton have already made the point I was going to about the anchor tag, but I fully understand and agree with why a span is used instead of a div in this example.

  • langsor

    Why would you choose to add the extra <div> tag? That makes no sense, you don’t need that hook and it adds no contextual meaning.
    My understanding as a (client-side/server-side coder/designer) is that you should use tags that have meaning for the content they contain. If there is no such tag, then you can opt for a <div> or <span>. Also use those generic tags for layout purposes (as in a content wrapper) — however, there is already a tag for a line-break <br /> and there is a tag for a group of sentences <p> — so why avoid these?
    Your argument about code generation doesn’t hold up either. If you’re going to stoop to generating html markup in php (yes, I’ve done it) then why not do so more generically and pass the class and text or node tree to that paragraph?

    Your code:
    <div class="help-note"><p>
         <span>Can you add a picture to the page about</span>
         <a href="..." title="Help us improve the article about 'Altocumulus clouds'">Altocumulus clouds</a>?
    </p></div>

    Either of these would make more sense in my opinion:
    <p class="help-note">
         Can you add a picture to the page about</br >
         <a href="..." title="Help us improve the article about 'Altocumulus clouds'">Altocumulus clouds</a>?
    </p>

    Or if you need more hooks for some reason:
    <p class="help-note">
         <span class="line-break">Can you add a picture to the page about</span> <a href="..." title="Help us improve the article about 'Altocumulus clouds'">Altocumulus clouds</a>?
    </p>

  • langsor

    P.S. This posting preview window does not work for beans! The posted result is nothing like what I formatted in the preview window.

  • willthiswork

    My questions are:

    1) Why do you have to spit structural, non-modifiable html tags through a php function in first place?

    2) Aren’t you supposed to just output the content of the help note?

    3) How can you programaticaly decide that every help note in the world has to be on 1 line?

    4) Isn’t the Decorator Pattern supposed to address these sort of problems?

    If we use a span, however, then we’re not only sticking to the sentence structure, but we’re also remaining flexible by adhering to the notion of progressive enhancement, by styling only the most specific cases and letting the more general, low-fidelity designs go unstyled.

    By the way this is the philosophy that led asp.net webforms to the horrible tag soup it is.
    The best approach is to style absolutely nothing. Exactly what php does now.

  • Control over code

    The problem with developers using span is that as a group you like to also apply inline styles that make it harder for us to clean up your mess with CSS.

    The third example of Tyssen’s post is the best.

    Programmers should do what they do best: write the code to make the thing work.

    Designers should do what they do best: make it look good, and usable.

  • http://www.sitepoint.com/articlelist/537/ Meitar

    Why would you choose to add the extra <div> tag? That makes no sense, you don’t need that hook and it adds no contextual meaning. My understanding as a (client-side/server-side coder/designer) is that you should use tags that have meaning for the content they contain. If there is no such tag, then you can opt for a <div> or <span>. Also use those generic tags for layout purposes (as in a content wrapper) — however, there is already a tag for a line-break <br /> and there is a tag for a group of sentences <p> — so why avoid these?

    Good questions, langsor. Two things: first, I used the wrapping <div> in order to add a needed stylistic hook. It’s unfortunate, but as we all know, sometimes you just need another element. :) Take a look at the old stand-by of amazing web designs, the CSS Zen Garden. There are plenty of “superfluous” elements in that document, but for similar good reason.

    Second, using a <br /> element is extremely inflexible. If I used that, then it would have been tedious to remove the linebreak in circumstances where the visual design did not call for one. In other words, the line break is more often the exception than the rule, and forcing a specific design use case in HTML is rarely a helpful thing to do.

    Your argument about code generation doesn’t hold up either. If you’re going to stoop to generating html markup in php (yes, I’ve done it) then why not do so more generically and pass the class and text or node tree to that paragraph?

    “Stoop”? I wouldn’t consider it that. Discretion is the better part of valor, and all that. :)

    How can you programaticaly decide that every help note in the world has to be on 1 line?

    You can’t; that’s my point exactly, willthiswork. You can also not programmatically decide that every help note in the world has to be on two lines. Hence the only logical conclusion of using a <span> instead of a <div> in this case.

    The problem with developers using span is that as a group you like to also apply inline styles that make it harder for us to clean up your mess with CSS.

    That’s unfortunately very true, COC. While annoying, it’s also an opportunity for improving precisely the kind of necessary cross-functional collaboration required to make a website, y’know, function. :)

  • W2ttsy

    have you thought about using Freemarker or something similar (not sure if FTL is available in PHP though) so that you end up with a bunch of HTML documents littered with hooks for the backend model objects?
    for example i end up having code that looks like this
    <p>Welcome ${user.firstName}</p>
    and it renders in the browser source as
    <p>Welcome John</p>

    i have been using freemarker in conjunction with Spring now for a while and I couldnt be happier. As long as the object i’m referencing in my freemarker file exists in the model, everything is golden. My back end team mates focus on building all the business logic needed for the app and I worry about the front end looking correct.

    in fact, if there is no freemarker interpreter available, then the HTML is still rendered in the browser, just with the placeholders on the screen. I have found that I can pretty much code all my prototypes with free marker tags directly in the HTML and then the transition between proto and back end integration is a matter of dragging and dropping the files from one folder to another! Has saved alot of time where i used to refactor the HTML source in a JSP or similar and then apply the JSTL tags to acheive the right data presentation…