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/
Related
Is it ever acceptable to nest heading tags within list item tags within the HTML5 nav element in an effort to have the navigation list items show up in outlines? This validates but is it semantically correct to have a heading on a navigation list item? Is there any way to get the navigation items to show up in outlines with HTML5? Or should I even care about this?
The HTML5 syntax rules allow heading elements h1, h2 etc. inside li elements. However, it (like all HTML specifications) define heading elements as being headings for something. This is implicit in earlier specs but made clearer in HTML5, which defines how headings participate in the division of a document into sections. A heading for an empty section, though formally valid, does not make sense, except perhaps as a temporary state where the content has not been inserted yet and will be added in a later version or with a script.
Technically, using <nav><li><h2>foo</h2></li>...</nav> would put “foo” into the outline, as if the document had a section with the title “foo”. But you would hardly gain anything that way, even if HTML5 outlines had some support. And they don’t; see he HTML5 Document Outline is a dangerous fiction.
My answer would be to just make your own div and wrap your nav-items in it. You can thereby change your font-size and all the other things you're willing to make out of it. Forget the header tag is what I recommend, I wouldn't see it much of an useful element in lists.
In CSS:
.myDiv {
font-size: 20px;
display: block;
border: 2px solid black;
}
And then assign it to the HTML
<div class="myDiv">Home</div>
<div class="myDiv">About</div>
and so forth. Hope this helps and that I understood your question!
Doing a code review, I noticed that a heading was using <span> tags instead of headings, so I suggested using an <h4> tag, to gain the semantic benefits. The context is a website footer, where there are various lists of links under different headings.
<span>Category 1 Links</span>
<ul>
<li>Link 1 in the footer</li>
<li>Link 2 in the footer</li>
<li>Link 3 in the footer</li>
<li>Link 4 in the footer</li>
<li>Link 5 in the footer</li>
</ul>
The counterargument was that <h4> is a "block-level" element, whereas an inline element was needed. Therefore he didn't think the element should be changed. (And yes, he knows CSS and is familiar with the display: inline; property.)
That sounds absolutely insane to me--goes against everything I always thought was best practice: separation of content and presentation, semantic web, the very purposes of HTML and CSS... yet in trying to formulate a response, I came across this section in the HTML 4.01 spec:
Certain HTML elements that may appear in BODY are said to be
"block-level" while others are "inline" (also known as "text level").
...
Style sheets provide the means to specify the rendering of arbitrary
elements, including whether an element is rendered as block or inline.
In some cases, such as an inline style for list elements, this may be
appropriate, but generally speaking, authors are discouraged from
overriding the conventional interpretation of HTML elements in this
way.
The alteration of the traditional presentation idioms for block level
and inline elements also has an impact on the bidirectional text
algorithm. See the section on the effect of style sheets on
bidirectionality for more information.
So here is the question: does this section make the issue sufficiently vague for there to be valid difference of opinion here, or is it (as I had thought) pretty clear in one way or the other? If this section is open to interpretation, are there any other W3C guidelines that are more concrete?
I don't want to get into opinions on this, I just want to make sure I'm understanding the spec and the W3C guidelines correctly: is there true ambiguity here, or not?
W3C specifications allow display: inline on heading elements. In general, HTML specifications do not restrict what you can do in CSS, and vice versa.
The section Block-level and inline elements that you quoted contains a recommendation (“discouraged”). It is a “should not”, not a “shall not” statement, i.e. not a conformance criterion. The motivation for the recommendation is not given, but generally such ideas are based on the fact that HTML documents may be processed by software that ignores style sheets, or may have author style sheets overridden, or otherwise gives preference to the defined meanings of elements rather than their CSS styling.
Even though the possibility of making a heading an inline element (in the sense of setting display: inline) is not mentioned here, doing so is part of one way of creating “run-in headings” (headings that appear inline at the start of a paragraph, rather than on a line of its own). Nowdays a better way to achieve that is display: run-in, as exemplified in the CSS basic box model WD. The basic point is still the same: it’s OK to turn a heading element from its default display: block to inline-like presentation.
Regarding the specific case presented, I don’t quite see why an inline element would be needed. The next element is ul, causing a line break (and vertical spacing) by default. And if the rendering of the ul is changed to inline with CSS, it is difficult to see why you could not do the same to an element that is logically a heading for the list.
First of all, the quoted section is indeed from the 14-year old HTML 4.01 specification. I do not remember ever reading anything of the type in the HTML5 specs. I personally think it was deemed a good remark at the time but has since been obsoleted by experience. Don't forget that HTML4 was the one to actually properly separate HTML and CSS, and as such contains 'mistakes' like the quoted remark that were later 'corrected'.
In essence, there should not be any implicitly locked relationship between your semantic markup and your styling. Like the hX elements, a div is also a block level element, but only because of the way it interacts with other elements, most specifically which elements it can contain - an inline element must not contain a block element while a block element can contain both inline and block elements, bar explicitly defined relationships such as ul > li and table > tr > td. Essentially the separation of semantics and presentation should be kept so strict that the specifications of the markup language HTML should never even mention the existence of the concept of stylesheets - stylesheets can be applied to anything, not just HTML, and HTML feeds so many more technologies than just browsers.
From a web developer's perspective, you are absolutely right. The block nature of a h4 element merely implies its relationship with potential child elements, and its default representation in the browser's default stylesheet. What the CSS developer then wants to do with his stylesheet is his own choice - for all you care he applies a display:table-cell rule to it if that properly fits his design.
TL;DR: There is no ambiguity, and you should always write your CSS to conform to how you want to display your HTML, not adapt your HTML to the requirements of the CSS. Using a span where an h4 is required is just plain wrong from a semantic (and SEO) perspective.
In my opinion, any typographic convention that you have ever seen in a book or other printed media is fair game for modeling a web page.
For example, I have seen text books with several columns, each with a header, and one could achieve this effect by using display: inline to a h4 tag.
In this example, whether h4 is on a stand-along block or part of a horizontal sequence will depend on the content and how you are trying to communicate ideas to your readers.
Consider how your page would render in a text-only browser that does not support CSS, would the raw ordering of the text make any sense? If so, then, your choice of HTML are probably valid.
On the other hand, if you took table tags and turned them into headers or list items, then you are probably going to get HTML that would not sound right if the page were read by some type of audio browser (think visually impaired people using a page reader).
Let semantics dictate the tags that you use and use CSS to get the visual layout that you need.
Hi I have about six months experience in web development.
I have the following observation,
I use <div> tags a lot, it gives me the ability to position the elements, to archive the elements,
and it seems I can use <div> tags to do everything, simply playing with its display property.
I've never had to use <ul> or <li> elements in combination, except for horizontal menu navigation, and I am not sure why you can't do it with <div> elements, but it seems to be the 'convention' for achieving a horizontal menu.
Did I miss something? Are there some properties that <li> elements have that are better or more useful than <div> elements?
Please don't restrict this question to only horizontal menu list; I want to know any scenario where you would use a <li> over something else.
Yes, you can do anything (more or less) strictly with div tags (with exceptions, like forms and inputs, and images, and what not). But that's not the point.
First, specific tags have default css applied to them. li's have bullets, for example. You can change these, but in many situations, it's just easier to use the tag that has the style you're looking for.
But the most important reason is what's called "semantic markup", which is the concept that which element you use corresponds to a semantic meaning. li means it's a list of items, so even if you have no CSS applied (such as when a screen reader reads a page aloud for blind person) then it still has meaning.
The only reason to use one tag over another is semantics. The purpose of HTML syntax is to provide meaning to the content that is being rendered.
A <ul> element is an unordered list. It means the content is a collection of items where order is unimportant.
A <div> element is simply a structural element with no semantics associated with it. You could certainly use <div> elements to create the styles typically associated with <ul> elements, but it would mean losing the inherent semantics of the original element.
If you wanted to maintain the original semantics with <div> elements, you could use the list role:
<div role="list">
<div role="listitem">...content...</div>
<div role="listitem">...content...</div>
<div role="listitem">...content...</div>
</div>
However, the WAI-ARIA roles model isn't very well supported, so you'd be better off using the basic markup of:
<ul>
<li>...content...</li>
<li>...content...</li>
<li>...content...</li>
</ul>
HTML tags should help to explain the intent of the layout. When you use div for everything, it says nothing about the content. ul/li makes it clear that you have a list of related items.
This was the motivation for the addition of many new tags in HTML5: to make the layout have more semantics, that make it more understandable to humans maintaining the code, and to screen readers. So yes, you can make a page look the way you want with only div's, but it will be harder to understand.
Now depends your needs you can use any tag for example if you want to create a custom select is not ok to use div because is more useful to use ul li, check this example: http://jsfiddle.net/RwtHn/1152/
Now if you want to determine a section in which you want to add different paragaphs, pics or other static elements is more that ok to use divs. Check this for ul li : http://www.w3.org/TR/html401/struct/lists.html andthis for divs: http://www.w3.org/wiki/HTML/Elements/div . Is not a rule when to use what to use but it an help you in web development if you are codding well.
Cheers.
Are both <h1><a ...> ... </a></h1> and <a ...><h1> ... </h1></a> valid HTML, or is only one correct? If they are both correct, do they differ in meaning?
Both versions are correct. The biggest difference between them is that in the case of <h1><a>..</a></h1> only the text in the title will be clickable.
If you put the <a> around the <h1> and the css display property is block (which it is by default) the entire block (the height of the <h1> and 100% of the width of the container the <h1> resides in) will be clickable.
Historically you could not put a block element inside of an inline element, but this is no longer the case with HTML5. I would think that the <h1><a>..</a></h1> approach is more conventional though.
In the case where you want to put an anchor on the header, a better approach than <a id="my-anchor"><h1>..</h1></a> would be to use either the id or the name attribute like this: <h1 id="my-anchor">..</h1> or <h1 name="my-anchor">..</h1>
In pre HTML 5 this one
<a><h1>..</h1></a>
will not validate. You can use it in HTML 5.
However, i would use this:
<h1><a>..</a></h1>
unless you need to add more than < h1 > inside the < a >
<a><h1></h1></a> is not W3C valid... Basically, you can't put block elements inside inline elements
<h1><a>..</a></h1> and <a><h1>..</h1></a> have always behaved almost the same, when style sheets do not affect the rendering. Almost, but not quite. If you navigate using the tab key or otherwise focus on a link, a “focus rectangle” appears around the link in most browsers. For <h1><a>..</a></h1>, this rectangle is around the link text only. For <a><h1>..</h1></a>, the rectangle extends across the available horizontal space, since the markup makes the a element a block element in rendering, occupying 100% width by default.
The following shows how a focused <a href=foo><h1>link</h1></a> is rendered by Chrome:
This implies that if you style elements e.g. by setting a background color for links, the effects differ in a similar manner.
Historically, <a><h1>..</h1></a> was declared invalid in HTML 2.0, and subsequent HTML specifications followed suit, but HTML5 changes this and declares it as valid. The formal definition has not affected browsers, only validators. However, it is remotely possible that some user agents (probably not normal browsers, but e.g. specialized HTML renderers, data extractors, converters, etc.) fail to handle <a><h1>..</h1></a> properly, since it has not been allowed in the specifications.
There is seldom a good reason to make a heading or text in a heading a link. (It’s mostly illogical and bad for usability.) But a similar question has often arised when making a heading (or text in a heading) a potential destination for a link, using e.g. <h2><a name=foo>...</a></h2> versus <a name=foo><h2>...</h2></a>. Similar considerations apply to this (both work, there may be a difference since the latter makes the a element a block, and before HTML5, only the former is formally allowed). But in addition, both ways are outdated, and using the id attribute directly on the heading element is now recommended: <h2 id=foo>...</h2>.
H1 elements are block level elements, and anchors are inline elements. You are allowed to have an inline element within a block level element but not the other way around. When you consider the box model and the HTML spec this makes sense.
So in conclusion the best way is:
<h1>Link</h1>
do you want to use a hyperlink <a href="…">/a:link, or do you want to add an anchor to your heading? if you want to add an anchor, you can simply assign an id <h1 id="heading">. you can then link it as page.htm#heading.
if you want to make the heading clickable (a link), use <h1><a></a></h1>/h1 > a – blocklevel elements first, and inline elements inside
Also, there is style hierarchy differences. If you have it as <h1>Heading here</h1>, The styles of the anchor will overrule the styles of the h1 element. Example:
a {color:red;font-size:30px;line-height:30px;}
WILL OVERRULE
h1 {color:blue;font-size:40px;line-height:40px;}
I think the <h1>text</h1> is the least problematic with weak or old browsers, but modern browsers and powerful search engines are supporting both it and <h1>text</h1>; So it's a good freedom and useful to use both to improve our web page.
«Hope that could be useful»
Both are correct. They depend on the sizing of the anchor tag which you want and how you want your website laid out.
You can do <h1>Home Page</h1>, in which case it would return: Home Page But with an Anchor.
Or you can do <h1>Home Page</h1> and it would return a H1 hyperlink instead of just heading an anchor to the H1, like so:
Home Page
However, mostly you cannot add links within H1 because it will just render it as an anchor onto the h1 rather than adding a hyperlink. However, I think I'm right in saying that you could see a difference in behaviour for this on different browsers.
But correct me if I am wrong. :)
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.