Is a wrapper <div> a violation of content-style separation? - html

It's been said that the goal of CSS is to provide visual presentation and the goal of HTML is to provide structure of the document. Well, thank goodness. It has gotten so much easier, especially compared to font tags!
But in practice, it seems that way many of us still rely on HTML to use CSS when it shouldn't be there. For example, it's common to see a <div id="wrapper"> to wrap around elements inside so the body can be centered. In pure HTML, it would never be used because it's meaningless and it's used ONLY for CSS.
Right? So doesn't using <div id="wrapper"> actually violate one of the fundamentals of content-presentation separation?

Kind of. But it doesn’t matter.
Principles like “separate content and presentation” are helpful because they help you achieve your goals, by making code easier to change. They’re not like nuclear safety regulations — contradicting them won’t risk anyone dying, so “violation” is a bit of a strong word.
Sticking in a wrapper <div> to work around the limitations in CSS (and/or browsers) is fine. <div> and <span> are intended for that very use, as they're defined to not convey any meaning (i.e. they don't alter the "structure" of the document). It doesn’t hurt the code.
If you can avoid it, great. But don’t worry if you can’t. There are bigger fish to fry.

In any case "wrapper" is a bad choice for an id. In general, wrapping DIV's are not used for simple alignment tasks alone (use a SPAN otherwise) and do provide/determine a structure for your web page. Therefore, in my opinion, wrapping DIV's do not violate the content-presentation separation.

You can use something like:
<div id="content_container">
<div id="section_container">
<h2></h2>
<p>stuff</p>
</div>
</div>
And I believe this gives correct structure to your document. Though it would probably be nicer to have elements for this (like <content> and <section>), because id can only be meaning full for us not for parsing the document. div have no actual meaning it's just a container for block elements that's all and so I believe it cannot violate content-presentation separation.
Having said all that you could also use <body> element to center your content (it is an element after all), but I'm not 100% sure if it work in old IE (old meaning IE 6).

If your DIV's ID has an exact equivalent in HTML5 (div id="nav", for example) then it's structural and, therefore, perfectly acceptable. div id="wrapper" is probably the equivalent of div id="article" or div id="section", so it's probably OK, although poorly-named, as Anzeo suggests.

It can do, though sometimes the div provides structure. We have to accept that CSS is not yet perfect and that compromises have to be made in our HTML. In particular in this case, when all browsers support the CSS3 pseudo-element ::outside ( http://www.w3.org/TR/css3-content/#wrapping ) I think that many wrapper divs will become unnecessary.

My personal opinion is wrappers have a very useful and necessary purpose although I dont use the term wrapper. Consider a div that has a set width of 200px but we want a border without effecting the width of the div we would need this solution:
div#posts {
width: 200px;
height: 200px;
}
div#posts-inner {
padding: 10px;
border: 1px solid #ccc;
}
<div id="posts"><div id="posts-inner">
<p>My Posts</p>
</div></div>
If you markup your CSS effectively you can avoid examples of less useful css declarations like:
#posts {
border: 1px solid #ccc;
}
If you put your CSS elements into context rather than assuming what its class represents
div#posts-wrapper {
border: 1px solid #ccc;
}
This would improve the separation of design and content elements in your css.

It's best to think of this in terms of semantics. You should be using the right tag for the right part of your part. HTML5 is a big step in this direction allowing the use of more tags such as 'article', 'nav' and 'section', which are give more semantic meaning than div.
However, div was a godsend for designers because it gave you a simple, block-level element with little semantic meaning other than to provide a 'divider', or 'section' of a page (much like the 'section' tag in HTML5). Not having anything else, it is perfectly acceptable to use in even a semantic sense because we didn't have anything else that had the same meaning and provided the same default characteristics.
It certainly doesn't violate the separation of style and content because it provides CSS with a block to do something with. You couldn't create most layouts on the web without using it AND keeping to a semantic structure!

It's common to see a "DIV
id='wrapper'" to wrap around elements
inside so the body can be centered. In
pure HTML, it would never be used
because it's meaningless and it's used
ONLY for CSS.
Is a containing wall not a structural piece of a building? I would argue that a containing wall is in fact one of the most common structural pieces you can find in elements.
So doesn't using DIV id=wrapper
actually violate one of the
fundamentals of content-presentation
separation?
No, A containing element (or a <div id="wrapper">) is just as much the structure of a document as a <header> <nav> <body> or <article>.
Even if it weren't considered structural, the goal of unobtrusive design is to separate as much as reasonably possible structure (HTML) from style (CSS) and behavior (JavaScript). In the end, unobtrusive design is really just a set of best-practice guidelines to follow to create more maintainable code.
Breaking the rules wont invalidate your code, and often times breaking the rules can create better, more maintainable code. As you design more and more, you will quickly learn that you sometimes have to go against the grain and ignore best-practices.

Related

Is changing default display property a good practice?

TL;DR Is it a bad practice to change default display property in my CSS?
Issue
Recently, in our project we had to position 2 header tags so they would look like one. They had the same font size and similar styling so the only issue was how to place one next to another. We had 2 different ideas on that and it le do a discussion on whether or not is a good practice to change default display property
So, our very basic code
<div class="container">
<h1>Header:</h1>
<h2>my header</h2>
</div>
The outcome we would like to have:
Header: my header
Note:
The code needs to consists of 2 different headings because on mobile version we want to display them in in separate lines (so leaving default display: block).
Approach #1: Use display: inline
This is pretty stright forward. Block elements became inline so they are positioned in the same line. The disadvantage of this approach is that default display properties of both h1 and h2 were changed.
Approach #2: Use float
H1 can be positioned on the left using float: left property. This approach leaves the default display property intact, but will requires some hacks if the .container is not long enough to fit both headers in single line.
The question
It all leads to a simple question: Is it a bad practice to change the default display property of HTML elements? Is it breaking the standard and should be avoided if possible? Or is it our bread and butter and it does not really matter, as long as code is semantically correct (so headers are placed in h1, articles are placed in article etc...)
Answering your main question:
tl;dr is it a bad practice to change default display property in my CSS?
NO
WHY?
A: Because it is all about semantics
Elements, attributes, and attribute values in HTML are defined (by
this specification) to have certain meanings (semantics). For example,
the ol element represents an ordered list, and the lang attribute
represents the language of the content.
These definitions allow HTML processors, such as Web browsers or
search engines, to present and use documents and applications in a
wide variety of contexts that the author might not have considered.
So, in your case if you really need to have 2 headings semantically then you can change their styles, including the display property.
However If you don't need to have 2 headings semantically, but only for purely cosmetics/design (responsive code), then you are doing it incorrectly.
Look at this example:
<h1>Welcome to my page</h1>
<p>I like cars and lorries and have a big Jeep!</p>
<h2>Where I live</h2>
<p>I live in a small hut on a mountain!</p>
Because HTML conveys meaning, rather than presentation, the same page
can also be used by a small browser on a mobile phone, without any
change to the page. Instead of headings being in large letters as on
the desktop, for example, the browser on the mobile phone might use
the same size text for the whole the page, but with the headings in
bold.
This example has focused on headings, but the same principle applies
to all of the semantics in HTML.
** Emphasis in the quote above is mine **
P.S - Remember that headings h1–h6 must not be used to markup subheadings (or subtitles), unless they are supposed to be the heading for a new section or subsection.
With all this above in mind, here is a few (good) approaches:
If you're doing the two headings purely for design then:
add a span inside of the h1, using a media query either using mobile first approach (min-width) or the non-mobile approach (max-width).
PROs - easily manageable through CSS, changing only properties.
CONs - adding extra HTML markup, using media queries as well.
h1 {
/* demo only */
background: red;
margin:0
}
#media (max-width: 640px) {
span {
display: block
}
}
<div class="container">
<h1>Header:<span> my header</span></h1>
</div>
If you need to use the two headings semantically then:
use flexbox layout.
PROs - no need to add extra HTML markup or the use of media queries, being the most flexible currently in CSS (basically the cons from option above mentioned).
CONs - IE10 and below has partial or none support, Can I use flexbox ? (fallback for IE10 and below would be CSS TABLES)
.container {
display: flex;
flex-wrap: wrap;
align-items: center;
/*demo only*/
background: red;
}
h1,
h2 {
/*demo only*/
margin: 0;
}
h2 {
/*640px will be flex-basis value - can be changed as prefered */
flex: 0 640px;
}
<div class="container">
<h1>Header:</h1>
<h2>my header</h2>
</div>
Sources:
W3C specs - 3.2.1 Semantics
W3C specs - 4.12.1 Subheadings, subtitles, alternative titles and taglines
tl;dr is it a bad practice to change default display property in my CSS?
No. As expressed by W3C themselves; HTML conveys meaning, not presentation.
As an HTML author, it's your job to structure a page so that every section of the page carries the intended semantics as described by the documentation, so that software (browsers, screen readers, robots...) can correctly interpret your content.
As a CSS author, it's your job to alter the default styling of correct markup to present it the way you want to. This includes changing the default display properties just as much as changing the default color.
Any software can, however, decide that certain usage of CSS properties changes the way they interpret your page. For instance, a search engine could decide that text that has the same color as their parent's background should carry no weight for their ranking system.
In regards to subheadings, it's considered incorrect to markup a subheading with an <hX> element. What you should do is to decide on one <hX> element, wrap it in a <header> and wrap subheading-type text in <p>, <span> or similar.
The following is an example of proper subheadings, taken from the W3C documentation:
<header>
<h1>HTML 5.1 Nightly</h1>
<p>A vocabulary and associated APIs for HTML and XHTML</p>
<p>Editor's Draft 9 May 2013</p>
</header>
Note that there's a discrepancy between the W3C specification and the WHATWG specification where the latter uses the <hgroup> element for this specific purpose, while the former has deprecated it. I personally go with W3C's example, but most software will still understand hgroup, likely for many, many years to come, if you prefer the WHATWG approach. In fact, some argue that WHATWG should be followed over W3C when the specs differ.
In your particular example, however, I'm not sure why you chose to split the <h1> into two elements in the first place. If what you marked up as an <h1> is actually supposed to be a generic "label" for the heading, then it should probably be considered a subheading instead. If you need to split it for styling purposes, wrap the two parts of text in <span> as such:
<h1>
<span>Header:</span>
<span>my header</span>
</h1>
tl;dr is it a bad practice to change default display property in my CSS?
Its a good practice but choose carefully when to use it because it can cause some critical structure mistakes.
Why is it a good practice
The display property is open for changes. It makes HTML simple and generic. HTML elements come with a default display value that match the general behavior - what you would usually want. But they dont have to be kept and manipulated around to imitate another display property. Think about <div> for example. Obviously most of the times you want it to have display: block;, but display: flex; is much more suitable once in a while.
Lets look at a really common example of lists. <li> comes with the display property of list-item that breaks the lines for every new item.
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
But horizontal lists are very common too. So why there is no special element for horizontal list items? Writing a special element for every common display behavior adds complexity. Instead, the convention, as also suggested by W3C is to set the <li> display property to inline.
ul li {
display:inline;
}
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
display: inline-block; as an alternative to float
float has been used massively in page layout for many years. The problem is that it wasnt created for this task and was originally designed to wrap text around elements. A well-known float issue is that non floated elements dont recognize floated children because they are being removed from the normal flow of the document. You also cannot centrally float an element. you are limited to left or right floats only.
display is much more suitable for layout many times. display: inline-block; tells browsers to place that element inline, but to treat it as though it were a block level element. This means that we can use inline-block instead of floats to have a series of elements side by side. It is more intuitive and eliminates floats <div class="clearfix"></div> which is an additional non semantic element in your HTML.
Floats are useful when there is a need to float an element so that other page content flows around it. But there is no need to always press them into the service of a complicated layout.
Things to avoid when changing display
When you change the display property remember:
Setting the display property of an element only changes how the element is displayed, NOT what kind of element it is.
<span> test case:
In HTML early versions <span> is considered an inline-level element and <div> is block-level. Inline-level elements cannot have block-level elements inside them. Giving the <span> a display:block; doesn't change his category. It is still an inline-level element, and still cannot have <div> inside.
HTML5 introduced content models. Each HTML element has a content model: a description of the element's expected contents. An HTML element must have contents that match the requirements described in the element's content model. <span> can contain only phrasing content. It means that still you cannot nest a <div> (flow content) inside a <span>. Giving <span> a display:block; still doesn't change it.
Avoid:
span {
display:block;
}
<span>
<div>
Still Illegal!
</div>
<span>
In conclusion, changing the default display property is certainly our bread and butter. Remember that it only changes how the element is displayed, NOT what kind of element it is and use it correctly.
Now about the original two heading issue:
With respect to the comments:
Let's assume for the sake of the question, that we need to have two
headings. Or let's forget about the headings for the time being. - by the author
And also to the comment:
This question is not about resetting the display value globally. Using
selectors to target only the specific elements is implied. The
question is what we should do with these elements once selected. - by the person who set the bounty
Two headings side by side not only to handle mobile layout changes, can be done in many ways. The original example is simple and correct so its actually a good way.
h1, h2 {
display: inline;
}
<div class="container">
<h1>Header:</h1>
<h2>my header</h2>
</div>
It follows HTML rules and doesnt require any additional hacks.
Sure changing the default behaviour is redundant and even can hit performance. As a subjective solution, would recommend to use flex (but i'm not sure about performance of it, altho you can google it), it's broadly supported, and doesn't change any element css properties, it's just a layout thing, check this out
.container {
display: flex;
justify-content: flex-start;
flex-direction: column;
align-items: baseline;
}
.container.mobile {
flex-direction: row;
}
web
<div class="container">
<h1>Header:</h1>
<h2>my header</h2>
</div>
<hr />
mobile
<div class="container mobile">
<h1>Header:</h1>
<h2>my header</h2>
</div>
Notice that h1 styles stay the same
Changing default css properties is not a good idea, and should be avoided to prevent unwanted shortcomings in your markup. Instead, you should give "id" or better "class" to all html elements you want to customize and do the styling for those.
Besides, using css like "h1", "div" etc. is the slowest way as the engine try to find all those elements in the page.
In your example, it doesnt matter to use display or float as long as you give your h1 elements a css class.
Also, using correct html elements for better semantics can be useful for things such as SEO etc.
best Practice is to group the two heading in hgroup and change the display property for mobile and other views using #media query.
<hgroup class="headingContainer">
<h1>Main title</h1>
<h2>Secondary title</h2>
</hgroup>
The HTML Element (HTML Headings Group Element) represents the
heading of a section. It defines a single title that participates in
the outline of the document as the heading of the implicit or explicit
section that it belongs to.
As hgroup defines a single title for a section ,therefore changing display property within hgroup is not bed practice.
UPDATE
It seems that I might've obscured the Plunker, since Anthony Rutledge obviously failed to see (or neglected to review) it. I have provided a screen shot with a few tips on how to use the Plunker.
PLUNKER - Embed
PLUNKER - iNFO
PLUNKER - Preview
Q & A
It all leads to a simple question: Is it a bad practice to change the default display property of HTML elements?
No, not at all. Matter of fact it's a very common practice of web developers (myself included), to alter not only properties of an element, but also attributes, and it's contents to name a few.
Is it breaking the standard and should be avoided if possible?
No, but perhaps the way one goes about doing it may break the code itself which IMO is a greater concern than standards. Standards of course plays an important role but not an essential one. If that were the case, then web browsers should comply under one common set of standards (I'm talking to you IE :P). Off the top of my head, here's things that should be avoided:
Using the table element for a layout
<table>
<tbody>
<tr>
<td><img></td>
<td><input type="button"/></td>
</tr>
...
Using inline styles
<div style="display: inline-block"></div>
Using inline event handlers
<div onclick='makeASandwich();'></div>
Or is it our bread and butter and it does not really matter, as long as code is semantically correct (so headers are placed in h1, articles are placed in article etc...)
Changing an element's display property is a very small yet fundamentally essential aspect of web developing. So yes I suppose it can be considered bread and butter, which would make semantics the parsley that's used as garnish and never eaten. Semantics is subjective, a way of thinking, it is not a standard. I believe a novice should be aware of it's importance (or at least how it's important to others), but should not be pontificating between an <article> and a <section> being semantically better than using a <main> and an <aside>. In due time, semantics will just feel right.
Approach #1: Use display: inline
I have never found a good reason to use display: inline because display: inline-block is a far better choice.
Approach #2: Use float
Floats are fragile antiques. Just like handling Grandma's bone china dinner plates, you must take certain precautions if you plan on using them. Be mindful of how to clear floats and don't throw them in the dishwasher.
Basically, if given only these 2 options, Approach #1 is a better choice, especially if using inline-block. I'd stay away from floats, they are counter-intuitive and break easily. I recall only using them once because a client wanted text wrapping around an image.
CSS & CSS/JS
Provided is a Snippet comprising of 3 demos:
Pure CSS solution utilizing display: flex.
Pure CSS solution utilizing display: table-row/table-cell.
CSS and minimal JavaScript solution utilizing display: inline-block and the classList API
Each of these demos are identical on the surface:
HTML
<section id="demo1" class="area">
<!--==Pure CSS Demo #1==-->
<!--======Flexbox=======-->
<header class="titles">
<h1>Demo 1 - </h1>
<h2>display: flex</h2>
</header>
</section>
This is the original markup with the following changes:
div.container is now header.titles
h1 text is: "Demo #n"
h2 text is: "prop:value"
section#demo#n.area is wrapped around everything.
This is a good example of semantics: Everything has meaning
You'll notice at the bottom of the viewport, are buttons. Each button corresponds to a demo.
Details on how each demo works as well as pros and cons are in the following files located in the leftside menu of the Plunker (see screenshot):
demo1.md flexbox
demo2.md disply: table
demo3.md classList
PLUNKER
These notes are not for the purpose of informing the OP of anything relevant to the question. Rather they are observations that I would like to address later on.
Further Notes
Demo 1 and demo 2 are powered by the pseudo-class :target. Clicking either one of them will trigger the click event It resembles an event because it's invoked by a click, but there's no way of controlling, or knowing the capture or bubbling phase if it actually exists. Upon further clicking of the first and second button, it will exhibit odd behavior such as: toggling of the other button then eventually becoming non-functional. I suspect the shortcomings of :target is that CSS handles events in a completely different way with little or no interaction with the user.
You should use:
$('element').css('display','');
That will set display to whatever is the default for element according to the current CSS cascade.
For example:
<span></span>
$('span').css('display','none');
$('span').css('display','');
will result in a span with display: inline.
But:
span { display: block }
<span></span>
$('span').css('display','none');
$('span').css('display','');
You can use flex box to arrange elements also, like this
<div class="container" style="display: flex;">
<h1>Header:</h1>
<h2>my header</h2>
</div>
Try to read this tutorial about flex, it is really great and easy to use
https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Semantic classes in Bootstrap

First of all, I apologize that this is probably a basic question, I tried searching other topics for an answer, but I'm still unsure.
I submitted a project where I needed to build a basic portfolio page using Bootstrap. I lost points for the following line of code:
<div class="container">
You need to add semantic tags. A semantic element clearly describes its meaning to both the browser and the developer. You can read more here: http://www.w3schools.com/html/html5_semantic_elements.asp
I understand why we should be using semantic tags however if I change the class from container to anything else it will adjust all the margins on the page. It was my understanding that Bootstrap recognized "container" and automatically applied Bootstrap properties to its children.
Am I doing anything wrong? Or am I just supposed to make a CSS rule that will apply margins to whatever I change container to?
Any help would be greatly appreciated, errors like this will become compounded with further projects!
I believe you are confusing tags and classes slightly: <div> is a tag - more specifically an element - and .container is a class. You can place the .container class on any element you want.
<p class="container"></p>
There are no definitive rules for class names, and as such they are not really a part of semantics, or SEO. A general suggestion is that they simply describe the element, not the styles.
Wherever you submitted your project most likely wanted to see a <section>, <article>, <aside> or some other HTML5 purely semantic element, which may or may not be proper semantics - kind of depends on what's inside it, and where it lies relative to the rest of the markup.
Generally speaking, the .container class is usually applied to generic elements in Bootstrap, and <div> is usually perfectly reasonable.
Another thing to consider, w3schools is a historically low quality source for web information, and usually a good indication that whomever is linking to it doesn't know very much about the web. I'd advise you to just start reading the tutorials and articles over at MDN, you'll learn a lot faster.

Should css class names like 'floatleft' that directly describe the attached style be avoided?

Lots of websites use class names like floatleft, clearfloat, alignright, small, center etc that describe the style that is attached to the class. This seems to make sense so when writing new content you can easily wrap (for example) <div class="clearfloat">...</div> around your element to make it behave the way you want.
My question is, doesn't this style of naming classes go against the idea of separating content from presentation? Putting class="floatleft" on an element is clearly putting presentation information into the HTML document.
Should class names like this that directly describe the attached style be avoided, and if so what alternative is there?
To clarify, this isn't just a question of what to name classes. For example a semantically accurate document might look something like:
<div class="foo">Some info about foo</div>
...
<div class="bar">Info about unrelated topic bar</div>
...
<div class="foobar">Another unrelated topic</div>
Say all these divs need to clear floats, the css would look something like:
div.foo, div.bar, div.foobar {
clear:both;
}
This starts to get ugly as the number of these clearing elements increases - whereas a single class="clearfloat" would serve the same purpose. Is it recommended to group elements based on the attached styles to avoid repetition in the CSS, even if this means presentational information creeps into the HTML?
Update: Thanks for all the answers. The general consensus seems to be to avoid these class names in favour of semantic names, or at least use them sparingly provided they don't hinder maintenance. I think the important thing is that changes in the layout should not require excessive changes to the markup (although a few people said minor changes are okay if it makes overall maintenance easier). Thanks to those who suggested other methods to keep CSS code smaller as well.
It's great until you re-design, and narrow is highlighted yellow, center converts better left-justified, and the image you called floatleft now belongs on the right.
I'll admit to the sin of using floatleft and clear as CSS class names, but it is much easier to maintain your CSS if you choose names that relate to the semantic meaning of the content, like feedback and heroimage.
Presentational class names
The HTML spec is clear on this issue:
There are no additional restrictions
on the tokens authors can use in the
class attribute, but authors are
encouraged to use values that describe
the nature of the content, rather than
values that describe the desired
presentation of the content.
Does clearleft describe the nature of the content? Not really. Eric Meyer made a joke about this a while ago.
Try to find a structural relation between the seemingly unrelated elements
Let's say you have paragraphs about ducks, paragraphs about monkeys and paragraphs about frogs. You want them have a blue background.
<p class="duck"></p>
<p class="monkey"></p>
<p class="frog"></p>
You could add this CSS rule:
p.duck, p.monkey, p.frog {
background-color: blue;
}
But aren't they all animals? Just add another animal token:
<p class="animal duck"></p>
<p class="animal monkey"></p>
<p class="animal frog"></p>
And change the CSS rule to:
p.animal {
background-color: blue;
}
It is hard and it might not always be possible but the important thing is not to give up quickly.
What if you can't?
If you have a lot of elements with absolutely no structural relation between them, that indicates a structural problem with your document. Try to decrease these elements. That said, grouping n CSS selectors on one rule is still better than adding n presentational class tokens in your HTML document.
Style classes should be semantic. This is a great article on semantic web page design (well, I found it really helpful anyway).
EDIT: I just read another article that makes some good points for using things like display: inline-block, display: table etc. instead of floats. That should help avoid those pesky floatleft and clearfix classes. Making them semantic is always up to you though.
The main problem with having classes named floatleft, clear or the like is the fact that changes in the design imply changes in the HTML markup. This should not happen, true separation between content and presentation is achieved only when you can re-use the same markup in multiple designs or even media (think sharing the same HTML between desktop and mobile versions of your site and only switching sylesheets).
Now, for a practical example :). To add on Fredrik's answer, LESSCSS allow you to hide styles declarations/mixins from developers. This way you can protect reusable components in your stylesheets without the danger of having them pop up in your HTML.
Sample markup:
<div class="branding">Company Name</div>
Sample less code:
// example of reusable functions
.noText() {
color: transparent;
text-indent: -9999px;
}
.clear-after() {
&:after {
content: ".";
display: block;
visibility: hidden;
height: 0;
clear: both;
}
}
.branding {
.clear-after();
.noText();
background-image: ...;
}
Of course, for mobile you might just want to have the company name in bold, without any other styling:
.branding {
color: pink;
font-weight: bold;
}
I think it depends on how you are using the styles.
Content should be named accordingly, as the style may change but the content will likely remain the same.
For instance, if you have a div that contains stock info, you should name the div something like div class="stockInfo", so that no matter what the presentation, you can change the styles and the name will not contradict those styles (as opposed to naming the div div class="yellow" and then changing the background-color to red).
However you will have "helper styles" and these should be named for what they do.
For instance, you will likely want to use a <br /> to clear some floats. In this case, it is perfectly reasonable to name it <br class="clear" /> and to give it a style of br {clear:both;}.
Again, most Web sites float their images right or left. To assist with this, you can set <img class="right" src="" /> and <img class="left" src="" /> and then have the styles to match, img.right {float:right;} etc.
So it depends on the usage.
Class names and ids that describe the function is better than using names that describe the styling of the element.
I usually end up not doing it religiously though, because it is in my opinion more convenient to i.e. clear floating elements by using the famous clearfix hack rather than adding clear:both all over the stylesheets.
But I think that LESS and SASS creates interesting opportunities to get the best out of both worlds, because you can have mixins and functions that describes some style and still have semantic correct names by just including whatever 'style' you want.
Instead of having this HTML and CSS
<div class="navigation roundedcorners">...</div>
.roundedcorners {
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
}
you could use SASS to create this mixin:
=rounded-corners
-moz-border-radius: 5px
-webkit-border-radius: 5px
border-radius: 5px
and include it into your .navigation class like this:
.navigation
+rounded-corners-5px
which would reduce your HTML to this:
<div class="navigation">...</div>
and therefore still get the advantage of having semantic correct names while having a convenient way to share styles between different elements.
Andrew; it's good to give sensible name to an class & id which easy to understand for you & your fellow member's which are working on that project. For me classes small , center , floatleft etc define nothing to me because when you give class center that's indicate that the element on the center but there are other properties also in that class like color, background etc
For example
<div class="wrap">
<div class="center">lorem</div>
</div>
css:
.center{margin:0 auto;}
in this example class center don't clear to me. but we can use them as a helper class.
For example
<div class="wrap">
<div class="panel center narrow">lorem</div>
</div>
css:
.center{margin:0 auto;}
from above example now it clear to me what the role of class center in that panel div
FOR MORE CHECK THESE LINKS :
What's the best way to name IDs and classes in CSS and HTML?
http://www.ronniesan.com/blog/entry.php?title=organizing-your-dom-elements-with-the-proper-ids
http://cssglobe.com/post/3745/my-top-10-most-used-css-class-names
If your question is:
Is it recommended to group elements
based on the attached styles to avoid
repetition in the CSS, even if this
means presentational information
creeps into the HTML?
Then my flat answer would be that in real world, semantic and presentation isn't everything. So my answer would be: it depends.
...depends if bandwidth is important to you... On a site with many visitors per hour, then the classnames could even simply be something like "c11" (yes, I've seen it) instead of meaningful, but looong class names.
...depends also if you perfectly know that when the look and feel will change, then the CODE will change also. (exemple: you redesign a site today in XHTML, but you perfectly know that when you'll re-do the CSS in 2 years, then you'll want the markup to be HTML5, so you will pretty much change the structure anyways...)
...depends also if you're already 3 days late on a delivery. When you're 3 days late, believe me, classnames like "nopadding" starts to appear, as you don't have anymore time to think straight about semantic (neither does your client).
Depends on so many things, I'd say... That's my "real life" point of view of your question.
From what I've seen, developers have the tendency to overload their HTML pages with way too many unnecessary classes and extra markup. These classes not only make the page size bigger (and thus the load time longer), they also crowd up the page and make it difficult to manage and modify at a later time.
Having things like center and float-left might be helpful when you're dealing with display text that was input by a user (such as a post on a forum), but for general markup purposes you're better off just adding text-align: center and float: left to the appropriate classes. This especially helps if you are trying to change the appearance of your site without changing the HTML much. The less you have hardcoded into your template, the easier it is to only have to change around the CSS when modifying your template. That bit alone is worth it to me.
As a general rule of thumb, you really should only give elements classes when it describes what the content is, not where or how it is being displayed. i.e. <span class="movie-information"> instead of <span class="bold">.
The only time I feel that it makes sense to give an element a class when it isn't necessary is if you are concerned with Search Engine Optimization. You should definitely read up on Microformats if you are interested in seeing how adding the right classes can actually help search engines. That being said, adding classes that describe how the page is visually displayed does nothing for the search engines.
The only time I would ever "group" classes is if they are either displaying the same thing, or if they are siblings. It gets really messy in your CSS when you have elements from all over your page defined together. You're much better off grouping your classes in your stylesheet in ways that you will be able to find them later, rather than saving a few lines by combining them.
I think this is where old meets new in web technologies. From times past, it has been difficult to unobtrusively render an outstanding web experience. These class names mostly came in handy when websites were changing webmasters to aid them in understanding the code. It served its cause well but with the new technologies of this day and age, I think this is slowly dying out - infact, it should be dead.
The question we should ask is, "Do we need to create a new class for every new innovative design that could pass as a template?". I do not think so. The markup on a site should do what it is meant for - markup. The class names used in the markup should be descriptive of the content and not its looks. The stylesheets - on the other hand - should be able to select elements on a document based on the information in the markup, and style them.
I want to relate this to the Rails association naming convention. Consider this...
class Post < ActiveRecord::Base
has_one :personifyable
has_many :personifications, :through => :personifyable
has_many :taggables
has_many :tags, :through => taggables
belongs_to :destroyers
end
Obviously, this is not a real model; it is something I am using to drive a point. Consider the case of a deeply nested dependency. These names will grow ridiculous - if they aren't already (i.e. in CSS, <div class='mediumwidth floatright centeredtext graytheme master'></div> or something of the like)
Now consider the case where you have different principles. Different developers and designers may - if not 'most definitely will' - have different reasons for using a specific naming convention. How would this affect refactoring time. I will leave that to your imagination. Also, if your business partner notices a new trend with sites themes that attracts traffic - more technically, assume this business partner has performed some experimental A/B testing and come up with some specs - you don't want to change the contents of the whole stack (ie HTML and CSS and possibly JS pages) to implement this new style.
In conclusion, keep styling hints out of your markup. Unobtrusively interact with the document to style and manipulate it. Sass gives you a fine way of styling a site while having your CSS mock your markup. jQuery is another awesome UJS library. HTML5 gives you methods too that make the markup more flexible and yields more information to CSS and JS.
I don't think adding a descriptive class name to your document is really a big issue. I find it's easier to work with explicit class names like "floatleft" as opposed to things that are purely semantic or reliant on the cascade. It's usually easier for later developers who don't have the document structure in their heads as well.
You don't want to use them for everything--you wouldn't want to add a class of floatleft to every li in a left-floated menu, but these kind of styles are very good when you need to do a specific thing to one or more elements, and you want to make other developers aware that you did it.
It's like putting in <div class="clear"> or even <div style="clear:both;">: maybe not the prettiest but it sure is obvious what you are doing.
My rule of thumb is: whatever makes you have to think less, do that.
EDIT: As I said in my comment above, this is most true for classes that refer to clearing and floats, i.e., things that are purely presentational, non-semantic, and yet must be referred to in the HTML. I think in this case it is actually preferable to indicate that you are using a purely presentational class, like floatleft, rather than forcing the float to be attached to some semantic element.
I am a developer before a programmer, so for me I use something like a "floatleft" css class as a sort of UtilityMethod.
Meaning, my css class is "floatleft"...and that's all that class does.
so if I say <div class="floatleft"></div> in my mind that is saying "make this div float to the left".
So if that Div also needs a blue background and is my main header it's going to have a different class for that and I end up with <div class="mainheader floatleft"></div>
Doing it this way also avoids issues with refactoring. If I am changing my design later, I will know that "floatleft" ALWAYS floats things left and nothing more.
I think, at the end of the day it is about what works for you. If your class name is descriptive of what it does, that does not really go against the rule of separating markup from styles. Another factor to consider is, are you the sole developer, or part of a team. If you are part of a team, or you know your code will be worked on later by other devs, you should establish, and document the naming conventions used.
I am currently contracting with Down Jones on some very large projects, and we have a rather lengthy document on naming conventions for our classes, including when to use camel-case, or dashes or underscores, as well as specific prefixes on the class name based on the project we work on. It sounds crazy, but when you have a dozen or so front-end devs working on stuff at the same time, it is a life saver!
You are saying something like this:
.red
{
color:red;
}
so in order to use this class:
<ul>
<li class="red">hello</li>
</li>
ALTERNATIVE SOLUTION
ul li
{
color:red;
}
Usage:
<ul>
<li>Hello</li>
</ul>
By this you can actually remove the presentation information from the content.
I personally name them things close to what they will be doing. Say I have a class that is on an image gallery and its a primary most used class it will be something like "gallery" or if I'm setting borders around things that are meant to be more decorative I'll name it "decoborder". I try to keep them semi short and somewhat related what task they provide. I don't like to do things like "small, large, H1underlined" or anything that can mimick another tag or function because that can just get confusing. Beyond that I think you should really name it in whatever way makes the most sense to you.
If the question is only one of naming, then for one specific class...
class="floatleft"
or
class="myClass"
or
class="gibberish"
....changes absolutely nothing. They are only different class names. The programming functions the same.
Either your content & presentation is separated, or it isn't... totally regardless of how you created the names.
For what it's worth, if I remember correctly the class keyword in HTML isn't currently used for anything other than CSS stylesheets. Thus, the example that you provided...
<div class="foo">Some info about foo</div>
...
<div class="bar">Info about unrelated topic bar</div>
...wouldn't really be a way of identifying data. I would suggest either the name or id attribute if you really want to identify data within your HTML tags. (They both have slightly different uses - name is generally used for server-side queries while id can be styled and is generally more versatile. IDs must be unique, but names don't have to be.) You can check further documentation using the W3C HTML specification.
In short - don't worry about tying content to presentation through your tag classes; until they're specifically used for anything else, they will not have any real effect on your raw content. As such, I'd say name your classes whatever you want, as long as it makes sense. Personally, I would err on the side of logical naming versus style-type naming (e.g. class name "editorcomment" instead of class "graybgfloatleft" or something like that), but in the end, your class names aren't going to tie your data to your presentation like an ID or a name would.
Good luck.
I've done both and I have to say nowdays I lean towards using non presentational classnames. I found this nifty framework called OOCSS https://github.com/stubbornella/oocss/wiki which helped me alot when I was creating a new layout for my web application and suited my requirements so well.
It is mostly because the definition of basic classes for spacing, headers and text works so well when you have to deal with alot of content. Because you use the same classes everywhere it helps make the layout better and maintainable.
Offcourse this means a element in your html can look like this: <div class="unit size1of3 lastUnit"> But isnt that what HTML is about? Making sure your information is presented properly.
I disagree on the whole redesign point, be honest, when you have to redesign your website most CSS goes out the door anyways. And, by dividing the CSS into proper classes for spacing/heading/text it becomes less likely to have conflicting css rules that mess stuff up like ul li div{}
Offcourse the classes do not describe the contents, but as CSS does not allow class inheritance and you have to support old technology like IE6...does it really matter? And do classnames like animal and duck really make for better html? Id like to think HTML is for the browser and when the browser renders it, thats for humans.
It depends, sometimes it makes sense just to add a class to let an element float. The problem with the semantic approach is that you will end up ball of mud of css classes. Sure, names like redLink or blackHeader have to be banned but sometimes you will need little helpers like "clear" or "floatLeft".
Read this article of Nicole Sullivan who explain this in deep.
There are two things that I feel get entirely left out of these discussions all too often. The first is WHY you would want to be all semantic or all not. The keywords are Branding and Skinning. Presentational class names may be justifiable if you work on some internal, departmental websites where branding and skinning will never in a million years get funding. On the other hand, customer facing sites, such as car manufacturers and department stores live in a world where every single new product that gets launched results in an entirely new skin for the website. New colors, new layout, new background images and all of this lead by designers who should be able to make the change purely in css so there's no chance they can break any working php (or what-have-you). There are also branded sites, where you have multiple skins, potentially running on the same site simultaneously. On sites with that requirement, you can't have visual changes impact html or you end up breaking every other brand just to update one of them. In these situations, semantic class names are a necessity.
The second thing that often gets left out is how to combat the problem of repeating groups of properties created by semantic class names, as in:
.content-nav {
float: left;
margin-right: 10px;
background-color: #ccc;
}
.content-nav .user-photo {
float: left;
margin-right: 10px;
border: solid 1px #000;
}
.content-nav .user-display-name {
float: left;
margin-right: 10px;
text-decoration: underline;
}
People often point this out as a drawback of semantic names, and I think that that's a valid point. On the other hand I would like to point out that there are tools that can help you keep semantic css DRY, such as LESS and SASS. I did see one other commenter mention this above, but I just thought that this point was worth highlighting.

Is not changing the body an HTML/CSS standard?

Often times I see something like this:
<body>
<div class="container">
</div>
</body>
Why not just do:
<body class="container">
</body>
You are perfectly free to do any of the following:
add a class or id attribute to the body element;
directly apply CSS to the body element, with or without class or id attributes; or
directly apply CSS to the html element, although without the class or id attributes and with some important caveats.
Any of these are perfectly legitimate uses of CSS and HTML.
Why <div id="container"/>? Through the years, many CSS techniques have employed arbitrary container elements for conceptual simplicity, to avoid certain cross-browser inconsistencies or because they were simply too complex to be achieved otherwise. A couple of more subtle reasons include that in older browsers, one could not apply CSS to the html element directly, and there were (and are) certain unusual or restricted properties for those elements—often for obvious reasons. (They were sometimes described as being "magic" for this reason.)
These all conspired to create a situation where to achieve almost any moderately complex layout, it was inevitably much easier to just start out with a squeaky-clean container element. Though the practice started as a means to an end it soon became just part of the scenery, and now many developers don't think twice about adding that sprinkling of extra markup.
No, there is nothing that says you can't add a class to the body.
Attaching a class to the body is actually quite common in various CMSes and is very handy for theming or styling specific pages.
From looking at your example, if you just want to use the body as a container, why even bother with the class? There should only be one body element, so just call that in your selector.
Walter, it may make sense if you needed to apply a slightly different subset of styling to a page with a custom body tag.
Using a wrapping div is usually for some presentational reason and make not make sense semantically; if you don't need it for your project, don't use it. Sometimes only using the body tag to contain the page is too inflexible for some layouts, and as Jordan says some old browsers cannot apply CSS to the root element.

Why is the <center> tag deprecated in HTML?

I am just curious as to why the <center> tag in HTML was deprecated.
The <center> was a simple way of quickly center-aligning blocks of text and images by encapsulating the container in a <center> tag, and I really cannot find any simpler way on how to do it now.
Anyone know of any simple way on how to center "stuff" (not the margin-left:auto; margin-right:auto; and width thing), something that replaces <center> ? And also, why was it deprecated?
The <center> element was deprecated because it defines the presentation of its contents — it does not describe its contents.
One method of centering is to set the margin-left and margin-right properties of the element to auto, and then set the parent element’s text-align property to center. This guarantees that the element will be centered in all modern browsers.
The Least Popular Answer
A deprecated tag is not necessarily a bad tag;
There are tags that deal with presentation logic, center is one of them;
A center tag is not the same as a div with text-align:center;
The fact that you have another way to do something doesn't make it invalid.
Let me explain because there are notorious downvoters here who will think I'm defending oldschool HTML4 or something. No I'm not. But the debate around center is simply a trend war, there is no real reason to ditch a tag that serves a valid purpose well.
So let's see the major arguments against it.
"It describes presentation, not semantics!"
No. It describes a logical arrangement - and yes, it has a default appearance, just as other tags like <p> or <ul> do. But the point is the enclosed part's relation to its surroundings. Center says "this is something we separate by
visually different positioning".
"It's not valid"
Yes it is. It's just deprecated, as in, could be removed later. For 15+ years now. And it's not going anywhere, apparently. There are major sites (including google.com) that use this tag because it's very readable and to the point - and those are the same reasons we like HTML5 tags for.
"It's not supported in HTML5"
It's one of the most widely supported tags, actually. MDN says "its use is discouraged since it could be removed at any time" - good point, but that day may never come, to quote a classic. Center was already deprecated in like 2004 or so - it's still here and still useful.
"It's oldschool"
Shoelaces are oldschool too. New methods don't invalidate the old. You want to feel progressive and modern: fine. But don't make it the law.
"It's stupid / awkward / lame / tells a story about you"
None of these. It's like a hammer: one tool for a specific job. There are other tools for the same job and other jobs for the same tool; but it was created to solve a certain problem and that problem is still around so we might as well just use a dedicated solution.
"You shouldn't do this, because, CSS"
Centering can absolutely be achieved by CSS but that's just one way, not the only one, let alone the only appropriate one. Anything that's supported, working and readable should be ok to use. Also, the same argument happened before flexboxes and CSS grids, which is funny because back then there was no CSS way to achieve what center did. No, text-align:center is not the same. No, margin:auto is not the same. Anyone who argued against center tags before flexbox simply didn't know enough about CSS.
TL;DR:
The only reason not to use <center> is because people will hate you.
I still use the <center> tag sometimes because nothing in CSS works as well. Examples of trying to use a <div> trick and failing:
<div style="text-align: center;">This div is centered, but it's a simple example.</div>
<br />
<div style="text-align: center;"><table border="1"><tr><td><div style="text-align: center;"> didn't center correctly.</td></tr></table></div>
<br />
<div style="text-align: center;margin-left:auto;margin-right:auto"><table border="1"><tr><td><div style="text-align: center;margin-left:auto;margin-right:auto"> still didn't center either</td></tr></table></div>
<br />
<center><table border="1"><tr><td>Actually Centered with <center> tag</td></tr></table></center>
<center> gets results. To use CSS instead, you sometimes have to put CSS in several places and mess with it to get it to center right. To answer your question, CSS has become a religion with believers and followers who shunned <center> <b> <i> <u> as blasphemy, unholy, and much too simple for the sake of their own job security. And if they try to take your <table> away from you, ask them what the CSS equivalent of the colspan or rowspan attribute is.
It is not the abstract or bookish truth, but the lived truth that counts.
-- Zen
According to W3Schools.com,
The center element was deprecated in HTML 4.01, and is not supported in XHTML 1.0 Strict DTD.
The HTML 4.01 spec gives this reason for deprecating the tag:
The CENTER element is exactly equivalent to specifying the DIV element with the align attribute set to "center".
What I do is take common tasks like centering or floating and make CSS classes out of them. When I do that I can use them throughout any of the pages. I can also call as many as I want on the same element.
.text_center {text-align: center;}
.center {margin: auto 0px;}
.float_left {float: left;}
Now I can use them in my HTML code to perform simple tasks.
<p class="text_center">Some Text</p>
You can still use this with XHTML 1.0 Transitional and HTML 4.01 Transitional if you like. The only other way (best way, in my opinion) is with margins:
<div style="width:200px;margin:auto;">
<p>Hello World</p>
</div>
Your HTML should define the element, not govern its presentation.
HTML is intended for structuring data, not controlling layout. CSS is intended to control layout. You'll also find that many designers frown on using <table> for layouts for this very same reason.
It's intended that markup, i.e. the HTML tags, represent meaning and structure, not appearance. It was badly mixed up in early versions of HTML but the standards people are trying to clean that up now.
One problem with letting tags control appearance is that your pages don't play well with devices for the handicapped, such as screen readers. It also leads to having lots and lots of tags in your text that don't help clarify the meaning, but rather clutter it with information of a different level.
So CSS was thought up to move formatting/display to a different language, which is separate from the text and can easily be kept that way. Among other things, this allows switching stylesheets to change the appearance of a Web page without touching the other markup. And to be able to do that for lots of pages in one swell foop.
The tools CSS gives you to do this are not always elegant, I'm on your side there. For instance, there is no way to do effective vertical centering. And horizontal centering, if it's not just text amenable to text-align, is not much better.
You have the choice of doing easy, effective and muddled or clean, elegant and cumbersome. I don't understand why Web developers put up with this mess, but I guess they're happy to have at least a chance to get their stuff done.
For text and images you can use text-align:
<div style="text-align: center;">
I'm centered.
</div>
You can add this to your css and use <div class="center"></div>
.center{
text-align: center;
margin: auto;
justify-content: center;
display: flex;
}
or if you want to keep <center></center> and be prepared in case its ever removed, add this to your css
center{
text-align: center;
margin: auto;
justify-content: center;
display: flex;
}
Food for thought: what would a text-to-speech synthesizer do with <center>?
CSS has a text-align: center property, and since this is purely a visual thing, not semantic, it should be relegated to CSS, not HTML.
Center is loved in HTML because it is a fast way to prototype your work without the hassle of setting up the CSS in the early stages of your work. Of course, having center used on your finished page becomes a chore in comparison to using CSS to create global centers for various elements. Thus, center will always have a place on the web, and there are still some old school forums around that format centered elements in their posts this way.
In other words, Love the center tag because it's cute and efficient when you need it!
PS: Marquee is also a classic HTML tag that is still around and that looks freaking awesome ^__^