Hidden features of HTML
Asked Answered
C

36

110

HTML being the most widely used language (at least as a markup language) has not gotten its due credit.
Considering that it has been around for so many years, things like the FORM / INPUT controls have still remained same with no new controls added.

So at least from the existing features, do you know any features that are not well known but very useful.

Of course, this question is along the lines of:

Hidden Features of JavaScript
Hidden Features of CSS
Hidden Features of C#
Hidden Features of VB.NET
Hidden Features of Java
Hidden Features of classic ASP
Hidden Features of ASP.NET
Hidden Features of Python
Hidden Features of TextPad
Hidden Features of Eclipse

Do not mention features of HTML 5.0, since it is in working draft

Please specify one feature per answer.

Cindy answered 5/6, 2009 at 4:58 Comment(0)
A
244

Using a protocol-independent absolute path:

<img src="//domain.example/img/logo.png"/>

If the browser is viewing an page in SSL through HTTPS, then it'll request that asset with the HTTPS protocol, otherwise it'll request it with HTTP.

This prevents that awful "This Page Contains Both Secure and Non-Secure Items" error message in IE, keeping all your asset requests within the same protocol.

Caveat: When used on a <link> or @import for a stylesheet, IE7 and IE8 download the file twice. All other uses, however, are just fine.

Aquino answered 5/6, 2009 at 4:58 Comment(13)
The // makes it protocol independent? I'm a little confused.Latrena
That’s not an HTML feature but a URL/URI feature.Jenelljenelle
Gumbo, it's still nice that browsers support it correctly in HTML.Limner
@eyelidlessness: It’s not just “nice” but essential for a browser to correctly support the full URI standard. And that’s not that hard.Jenelljenelle
@Gumbo: True, it's a URI feature, but I figured it was good enough to bend the rules and include here. And I don't expect a Hidden Features of the URI Spec anytime soon. :)Aquino
This presumes that the server in question supports SSL. That's not always the case.Pension
Could this eliminate a bit of string building in the Google Analytics JavaScript code?Gamez
@alex, i have wanted it to, but sadly they also pull from a different subdomain.Aquino
Question, why do you need double slashes? Isn't just one slash independent of the protocol? Won't that just use the current protocol, or does it default to http in some way?Baten
one slash is relative from the domain part, not from the protocol partKokoruda
IE is so incredibly DUMB! Why the f*** hell does it DL the file twice?Killoran
why does it ignore all standards with a vengeance, for that matter?Carlynne
There's one major drawback: when a file is saved to disk and accessed using the file: protocol, the browser won't be able to find the resource (e.g., of a CDN or some other external server).Munitions
M
138

The label tag logically links the label with the form element using the "for" attribute. Most browsers turn this into a link which activates the related form element.

<label for="fiscalYear">Fiscal Year</label>
<input name="fiscalYear" type="text" id="fiscalYear"/>
Maxson answered 5/6, 2009 at 4:58 Comment(13)
yes, amazing how few sites actively use this. I have seen sites using js to do this...Hunfredo
That's a good practice to use label tags for form fields. But really, that's not a hidden feature.Tocharian
Discovered this one quite recently.Paloma
cagdas, there aren't really hidden features in HTML, it's a specified standard.Limner
To expand on the answer, one can also wrap an input with a label and omit the for attribute: <label>Fiscal Year <input name="fiscalYear" type="text" /></label>Limner
Also, +1 because while this is an HTML basic, too many developers remain ignorant of it.Limner
Huh, this is actually one of the first things I learned about HTML... still +1Dagmardagna
@eyelidlessness: Yes, but now you can put your label at an arbitrary place in your HTML. Also I thought nesting them gave weird rendering issues somehow, but I don't remember what the problem was.Hunfredo
Using checkboxes and radio buttons without it should be a crime.Lona
Knew it almost from the beginning. Actually, mostly it is used with check boxes. But no wonder that it will do for other elements.Teniers
I have seen tons of HTML which does not use this, so if not "hidden" it's still certainly a "lesser-known" feature.Materialist
@eyelidlessness: with some browsers (IE), that does not work properly. For example, if you click the label for checkbox, it will not toggle.Appointed
I was surprised to discover the link behaviour in GUI browsers - but I'd already been using label/input pairs for accessibility in text and speech browsersMold
M
136

The contentEditable property for (IE, Firefox, and Safari)

<table>
    <tr>
      <td><div contenteditable="true">This text can be edited<div></td>
      <td><div contenteditable="true">This text can be edited<div></td>
    </tr>
</table>

This will make the cells editable! Go ahead, try it if you don't believe me.

Mohock answered 5/6, 2009 at 4:58 Comment(10)
The question calls for features which are not introduced by HTML5Juan
Works in Safari 4, too! No idea if it works in version 3, though.Thickknee
David Dorward, It's not exactly fair to say it's introduced with HTML5, as contentEditable was introduced by MS in IE 5.5, but yes it hasn't been standardized until HTML5; Tyson & Steve, contentEditable was introduced to Safari in version 2.0, but many important formatting methods weren't added until 3.x; Victor H Valle, depends on your doctype. HTML 4 should expand it to ="true" when collapsed.Limner
@Limner OK, so it was introduced as a proprietry thing. It isn't part of any HTML recommendation, which the question strongly implies as a requirement by ruling out the HTML5 draft.Juan
the try it link doesn't lead to an appropriate exampleDiscursive
Wow, fun! Also, margins-editable, apparently. At least in Firefox 3. @CrazyJugglerDrummer, you can edit it yourself and click the button. You don't even need a div: <td contenteditable>...</td> works just as well.Brunhilda
@Binoj - Absolutely not. "The contenteditable attribute is an enumerated attribute whose keywords are the empty string, true, and false" - w3.org/TR/html5/editing.htmlJuan
Better yet, add the following as a bookmarklet to let edit any web page you're on: javascript:document.body.contentEditable='true';document.designMode='on';void(0);Amalgamate
This is hilarious! Works in pretty much all of the modern browsers. Looking for a way to submit the value of the editable element to server side script (preferrably without the help of JS). Any ideas? Cause' that'd be the coolest thing ever!Salzhauer
I think it's mainly useful in a javascript context, where you allow the user to edit a section of code if they wish, and then submit that content via js.Aqualung
F
102

I think the optgroup tag is one feature that people don't use very often. Most people I speak to don't tend to realise that it exists.

Example:

<select>
  <optgroup label="Swedish Cars">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
  </optgroup>
  <optgroup label="German Cars">
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </optgroup>
</select>
Forgo answered 5/6, 2009 at 4:58 Comment(5)
Unfortunately, browser implementation of menu hierarchy leaves much to be desired. I suspect optgroup doesn't get much use because its relevant use cases are few and far between.Limner
One level should be supported in all browsers. A web-forum I'm apart of else where uses it in some screens to divide the forum list into the same sections as used on the main page.Person
@staticsan. I agree it is useful for small categorisation of a number of items.Beaver
@eyelidlessness: I see drop-downs all the time that indent elements or use some kind of 'header' text like ---category---.Muoimuon
This is a neat feature I did not know about!Seligmann
C
99
<img onerror="{javascript}" />

onerror is a JavaScript event that will be fired right before the little red cross (in IE) picture is shown.

You could use this to write a script that will replace the broken image with some valid alternative content, so that the user doesn't have to deal with the red cross issue.

On the first sight this can be seen as completely useless, because, wouldn't you know previously if the image was available in the first place? But, if you consider, there are perfect valid applications for this thing; For instance: suppose you are serving an image from a third-party resource that you don't control. Like our gravatar here in SO... it is served from http://www.gravatar.com/, a resource that the stackoverflow team doesn't control at all - although it is reliable. If http://www.gravatar.com/ goes down, stackoverflow could workaround this by using onerror.

Conjugation answered 5/6, 2009 at 4:58 Comment(4)
Aha... if this is what think it is, i should know this earlier when i truly needed that. :/Paloma
to clarify, onerror is a javascript event (just like onclick) which lets you do something when an image fails to load.Skirting
Daniel Silveira, will you clarify that this does, in fact, run onerror code in the case of broken (eg 404) images? Regardless, this is a DOM feature, not an HTML feature per se.Limner
I had a numpty use this one, pointing to a nonexistant image, recursive anyone???Brucine
G
99

My favourite bit is the base tag, which is a life saver if you want to use routing or URL rewriting...

Let's say you are located at:

www.anypage.example/folder/subfolder/

The following is code and results for links from this page.

Regular Anchor:

<a href="test.html">Click here</a>

Leads to

www.anypage.example/folder/subfolder/test.html

Now if you add base tag

<base href="http://www.anypage.example/" />
<a href="test.html">Click here</a>

The anchor now leads to:

www.anypage.example/test.html
Giveandtake answered 5/6, 2009 at 4:58 Comment(18)
me neither... have to check it a bit more.Reddish
You could also just use /images/image.png, with a leading slash. :-)Yea
The base tag is a nuclear option - it's the equivalent of #define: if you don't keep track of it, make it really clear to future developers, and make it a really low level part of the site architecture it can lead to frustrating non-obvious bugs. I've never needed this, use with caution.Glaciology
I've had fun with it interfering with JavaScript and CSS in unexpected ways. Best leave base well alone and handle the problem with server side logic.Juan
It can only really interfere with things in a very expected way - it sets the base path for the page. I'm using it with CSS and JavaScript (including jQuery) with absolutely no problem.Murial
Things get unexpected when different browsers handle it differently.Juan
Yes, I have also seen the base tag interfere with my JavaScript when trying to dynamically load CSS files into the page. Also, a bug in IE6 requires you to explicitly close the tag (</base>), which is invalid. Conditional comments can help with that.Jerk
Note that the base URL is applied to every relative URL and not just to relative URL paths. So the reference #top would be resolved to “top” in the root index document and to “top” in the same document.Jenelljenelle
To expand on Gumbo's comment, the base tag works great for the combination of relative paths and rewritten URLs, but it means you must expand anchor links to their "full" relative path. So to link to #top on /some/page, your href should be some/page#topLimner
I find this extremely handy in situations where I have to 'view source' and download the HTML of a page to work with it. Once the source is downloaded, you can add a BASE element with the appropriate href attribute. This way, you can work locally after downloading only the source HTML... no need to download all the javascript, css, and images.Bonneau
I've found it useful when I'm doing some sort of url redirection behind the scenes but want it to be transparent to the user. Sure, you're viewing example.com/page/foo/query/arg1/arg2, but the server is really serving up example.com/fooquery.php, and all of the relative links assume this.Selfwinding
@ Mathias Bynens - Actually, the issue discussed is a problem with a link scanner - and I'm sure as hell not writing code to infect my web page just for the benefit of a link scanner.Murial
It's also got the terrible side effect of modifying anchor links (you know, #stuff) so they point to <base>#stuff.Dordrecht
@Dordrecht - it does do that, but it's not a side-effect - it's by design.Murial
@Sohnee: okay, it's not a side effect to the spec. But maybe it's a side effect to what people would like.Dordrecht
For an interesting use case for the base tag, see jQuery Mobile: jquerymobile.com/demos/1.0a1/#docs/pages/docs-navmodel.htmlLengthways
@Yea But having a leading slash needs some other code to deal with local development where the directory structure might be a few levels deeper than the actual production domain. This usually manifests itself in environments where multiple relatively smaller projects are developed in the same local scope.Twandatwang
You can also use <a href="/test.html">Click here</a>Hillell
B
96

The <kbd> element for marking up for keyboard input

Ctrl+Alt+Del

Blackpoll answered 5/6, 2009 at 4:58 Comment(4)
Is there anything special about <kbd> beside it be a different font format? if not here is a list of other formatting tags? w3schools.com/tags/tag_phrase_elements.aspGroff
Not especially, just not well known I don't thinkBlackpoll
Nothing by default, but it's cleaner to mark up the element with CSS like how SO does.Incoordinate
Wasn't aware it existed, that's fun.Aqualung
M
84

Not very well known but you can specify lowsrc for images which will show the lowsrc while loading the src of the image:

<img lowsrc="monkey_preview.png" src="monkey.png" />

This is a good option for those who don't like interlaced images.

A little bit of trivia: at one point this property was obscure enough that it was used to exploit Hotmail, circa 2000.

Mohock answered 5/6, 2009 at 4:58 Comment(6)
This I didn't know. Can it be used for "loading" animation?Hunfredo
I'm getting a fraud warning in Opera from that "exploit Hotmail" link. :oFungistat
yeah, I use Opera as well and get that fraud warning... what is it?Extrauterine
It's a security website, it's safe.Confirm
But this attribute it proprietary. msdn.microsoft.com/library/ms534138(VS.85).aspxJenelljenelle
This attribute has been deprecated since HTML4 - you shouldn't use it in production websites.Arytenoid
L
84
<blink>

Must be used for anything important on the site. Most important sites wrap all of content in blink.

<marquee>

Creates a realistic scrolling effect, great for e-books etc.

Edit: Easy-up fellas, this was just an attempt at humour

Lasonyalasorella answered 5/6, 2009 at 4:58 Comment(12)
As I know, marquee is not html specific, but depends on IETureen
blink is heavilty discouraged, unless you want to annoy users. Its support isn't perfect either.Discursive
Perhaps the question ought to have specified that you shouldn't list features that we want to remain hidden.Adamite
...I've used <blink>, as part of a psuedo-terminal styling for a div displaying code (:before {content: "drthomas@house: ~$";} :after {content: "_"; text-decoration: blink; } ...it was awesome. I should probably seek help. =]Boong
Those two tags single-handedly (or is it double-handedly) induce the necessary rage to boil the oceans (who needs 128bit filesystems to do that?).Endoparasite
on early ages of html pages, these were web developers' secret weapons to have the wow effect from viewer. But those days are past now, they should be removed from html permanently :)Desmid
<marquee><blink>The MOST annoying HTML tags ever!!!</blink></marquee> These are not hidden they are just not used for a reason.Groff
I wrap my entire page in Marquee and Blink because I am just that coolIntegration
Also worth noting is that marquee nested inside blink does not work. Blink must be nested inside marquee for awesomeness - jsbin.com/evesu3/3Wardlaw
Please. The only legitimate use for <blink> is: Schroedinger's cat is <blink>not</blink> dead. (I thought this was on xkcd, but I can't find it at the moment.)Canalize
Very funny, but still a -1 because blink and marquee are hideous and I would hate for people to think otherwise :)Murial
For what it's worth, CSS3 came out with marquees: w3.org/TR/css3-marqueeLicit
J
67

DEL and INS to mark deleted and inserted contents:

HTML <del>sucks</del> <ins>rocks</ins>!
Jenelljenelle answered 5/6, 2009 at 4:58 Comment(8)
Definitely not used enough.Limner
@eyelidlessness: there's simply not enough situations where marking deleted/inserted text is that useful.Muoimuon
I could swear that StackOverflow used <ins> and <del> on the Revisions pages at some point awhile back, but now it uses <span class="diff-add"> and <span class="diff-delete">. :(Materialist
@systemPAUSE That's disappointing. So much for semantic markup.Apiary
@Muoimuon wiki revision histories? plenty of use cases for itMold
@Horus: sure you can find uses, but in the grand scheme of things that's still not a huge amount of situations.Muoimuon
@DisgruntledGoat: guess I've been involved in more article management apps than is the norm thenMold
Even better is that it has a datetime="some date" and cite="some citation" attributes.Aggregate
M
58

The button tag is the new input submit tag and a lot of people are still not familiar with it. The text in the button can for example be styled using the button tag.

<button>
    <b>Click</b><br />
    Me!
</button>

Will render a button with two lines, the first says "Click" in bold and the second says "Me!". Try it here.

Mohock answered 5/6, 2009 at 4:58 Comment(9)
Shame about it being broken in IE < 8. It is possible to work around the issues, but that can be painful, and sometimes you hit security protection running between the web server and the server side programming environment.Juan
It's still usable you just need to use type="submit" on it.. its useful as you can put elements inside, for example- using a span inside a button is often used to ensure you can correctly css style a button (ie, without the browsers implied padding).Boater
But IE < 8 will submit the content of the element, not its value. I believe some versions will always treat it as a successful control (even if it wasn't clicked) too.Juan
And if you make it <button contenteditable> you can change the button text too! Points to anyone who could find a valid use for it. :)Gaudreau
I never understood why there was an "input" type of submit. It's not inputting anything, just submitting what you inputted on other fields.Muoimuon
@DisgruntledGoat: its name/value pair will actually be sent. Useful if you have more than one button in a form (e.g. edit, delete, moveup, etc) and want to distinguish the button pressed. Unfortunately the same doesn't work for button in IE<8, it astonishingly sends the name/value pairs of ALL button elements.Orta
You can safely use the button element in IE <8, provided you don't give it a name or a value that you care about. It's no good when you have more than one button in the same form, and want to know which was clicked to trigger the activation.Arytenoid
On April Fools day I once put the entire site in one big <button>Killoran
I always use <button> and not <input type="button" /> because it is very easy for styling with CSS, if you have <input> for text fields. E.g. button { float:right } input { width:100px }Charlotte
C
56

Specify the css for printing

<link type="text/css" rel="stylesheet" href="screen.css" media="screen" />
<link type="text/css" rel="stylesheet" href="print.css"  media="print" />
Cindy answered 5/6, 2009 at 4:58 Comment(3)
Discovered that some weeks agoCupola
If you haven't dealt with this before, I hope that you haven't made any production websites before...Aqualung
how can this be considered hidden?Knead
S
54

the <dl> <dt> and <dd> items are often forgotten and they stand for Definition List, Definition Term and Definition.

They work similarly to an unordered list (<ul>) but instead of single entries it's more like a key/value list.

<dl>
  <dt>What</dt><dd>An Example</dd>
  <dt>Why</dt><dd>Examples are good</dd>
</dl>
Skirting answered 5/6, 2009 at 4:58 Comment(10)
Additionally, the dl/dt/dd semantics are appropriate for similar lists (eg. the structure has been recommended for dialogues).Limner
The default presentation isn't that nice, but people forget that the elements can be styled many ways with CSS.Muoimuon
I agree. They're great semantic elements that often get left out.Roturier
The more interesting thing that is often forgotten is that the format is key/value/value/value/value/key/valueJuan
@Limner It's semantically bankrupt for dialog, though. A person being what they say is a philosophical postulation, not an obvious semantic relationship.Mccloud
DD => Definition Description :)Dower
@D_N, the elements' semantics themselves, per spec, are broader than you allow for.Limner
@Limner Just because the spec suggests it doesn't mean it makes sense. Doesn't line up with its own definition. (Not trying to pick a fight. But semantics flow from definitions and such; the HTML4 spec suggests it could be used that way, but gives no rational for why that meets up with the definition it had already given.)Mccloud
@D_N, I think where the disagreement lies is that I consider the suggested uses to be a part of the definition and semantics, rather than separate from and contradictory to it.Limner
@D_N and @Limner - check out Bruce Lawson's note on marking up a conversation semantically... plus the jury is still out on the HTML5 dialog element... brucelawson.co.uk/2006/…Murial
G
52

Not exactly hidden, but (and this is IE's fault) not enough people know about thead, tbody, tfoot for my tastes. And how many of you knew tfoot is supposed to appear above tbody in markup?

Glaciology answered 5/6, 2009 at 4:58 Comment(8)
I heard of this last days as i had to work some sites out for php (I didn't work with web-development through my career before) its nice, you can make really nice designed tables with that.Cronus
boris callens, Yeah, tbody is implied if none of thead, tbody and tfoot are present.Limner
If IE5 had implemented TBODY properly, then more people would use it. This was the main problem several years ago. Mozilla and Opera supported scrolling TBODY which was really cool; unfortunately, IE5 did not.Person
I didn't know you didn't have to use tbody and thead.Upturned
They are useful for printing because it should put the thead and tfoot at the top and bottom of each page. It's a shame there's no mechanism for repeating thead in the browser, when you have long long tables.Muoimuon
I knew that tfoot went above tbody, and I think it's pretty stupid. I put my tfoot below, where it made sense, got a validator error, moved the tfoot above the tbody (confused but always compliant), and guess what?! When you try to highlight the table, the browser (FF at least) highlights the foot BEFORE the body, even though it is visually below the body! And then!!! when you copy it to a text editor, it's ABOVE the body visually. Totally arbitrary rule.Kleist
@Anthony: makes sense if you have a slow connection, it means you can see all the headers and footers while the table content is still loading.Apiary
th is sometimes left out as well.Licit
M
50

The wbr or word-break tag. From Quirksmode:

(word break) means: "The browser may insert a line break here, if it wishes." It the browser does not think a line break necessary nothing happens.

<div class="name">getElements<wbr>ByTagName()</div>

I give the browser the option of adding a line break. This won't be necessary on very large resolutions, when the table has plenty of space. On smaller resolutions, however, such strategically placed line breaks keep the table from growing larger than the window, and thus causing horizontal scrollbars.

The there is also the &shy; HTML entity mentioned on the same page. This is the same as wbr but when a break is inserted a hypen (-) is added to signify a break. Kind of like how it is done in print.

An example:

Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­Text­

Mohock answered 5/6, 2009 at 4:58 Comment(7)
Be careful because there's poor browser support on this oneNickynico
"IE8 as IE8" does not support it and it's buggy in Safari 3.0 for windows. Other than that support is pretty good. Refer to the compatibility chart in the link.Mohock
Hmm sitepoint reference marked this tag as deprecated and useless, who's right ? reference.sitepoint.com/html/wbrNickynico
It may well be deprecated as part of the HTML spec but it still works in browsers. Whenever in doubt, go with the QuirksMode verdict (compatibility tables now sponsored by Google).Mohock
Seems like this would be a very useful thing to include in the next css standard!Benedikta
&shy; seems to be slightly better supported according to quirksmode.org/oddsandends/wbr.html#t02. (Assuming most Firefox users update regularly; or at least more often than IE users).Fitch
<wbr> is not in W3C HTML4 standard: w3.org/TR/html4/index/elements.html And remember that XHTML is just HTML4 in XML.Mezzo
C
43

A much underused feature is the fact that just about every element, that provides visible content on the page, can have a 'title' attribute.

Adding such an attribute causes a 'tooltip' to appear when the mouse is 'hovered' over the element, and can be used to provide non-essential - but useful - information in a way that doesn't cause the page to become too crowded. (Or it can be a way of adding information to an already crowded page)

Connote answered 5/6, 2009 at 4:58 Comment(5)
Yes, the "title" attribute is quite useful—especially for elements that are meant to be clicked.Chasseur
The tooltip that appears is browser-specific. Not all browsers will display the title attribute the same. But it is a nice feature that I certainly use.Roundelay
The title attribute is useful, but only when used appropriately. Most browsers only render the tooltip for a few seconds before it disappears. I hate it when designers feel the need to fill up the title attribute with 3 or 4 lines of text which causes you have to mouse over, then mouse on again to read the rest of it.Agriculturist
Using this in connection with jQuery equals awesomeness.Yecies
Levi - can you give some examples?Connote
C
38

Applying multiple html/css classes to one tag. Same post here

<p class="Foo Bar BlackBg"> Foo, Bar and BlackBg are css classes</p>
Cindy answered 5/6, 2009 at 4:58 Comment(9)
Those are HTML classes, not CSS classes. CSS doesn't have classes (it has class selectors). HTML classes are usful for things other than CSS.Juan
Yes, that's why VS should learn not to nag about missing classes (some of us use classes for JS...)Hunfredo
Wow! I simply cannot get over the fact that people find this to be a "hidden" feature. Boy do I feel stupid about posting some "really hidden" features because people who upvoted this will probably not even come close to fathoming what extending a DTD means.Mohock
Be aware that Internet Explorer tends to ignore or mistreat CSS rules with multiple classes, like p.foo.bar { color: #000 }.Jerk
avdgaag, why dont you use syntax like p.foo,p.bar instead?Latrena
d03boy, p.foo, p.var is not the same as p.foo.bar. The former selects any paragraph with either the class "foo" or "var", the latter selects an paragraph with both classes.Limner
The thing regarding HTML classes is a good point, because it brings me onto a point- html should not be made aware of css.. you 'should' be able to create html, and pass it to a designer that can implement their design without needing to change the html (not quite the case yet ;)).. so this comes down to your naming and way you use classes.. don't create classes to target css properties.. use classes to identify what the element 'is'.Boater
IE6 only takes the last class. So if you have 2 declarations: ".text" and ".good" in your css. and you add a declaration for ".text .good", the properties will only apply to .good.Giveandtake
Technically, "Foo Bar BlackBg" is a single class, and p.foo is just syntactic sugar for p[class~=foo] (see spec). It is easier to think about it as having multiple classes, though.Mammiemammiferous
M
34

We all know about DTD's or Document Type Declarations (those things which make you page fail with the W3C validator). However, it is possible to extend the DTDs by declaring an attribute list for custom elements.

For example, the W3C validator will fail for this page because of behavior="mouseover" added to the <p> tag. However, you can make it pass by doing this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
[
<!ATTLIST p behavior CDATA #IMPLIED>
]>

See more at about Custom DTDs at QuirksMode.

Mohock answered 5/6, 2009 at 4:58 Comment(6)
Of course, this makes it "Valid: Your custom markup language" and not "XHTML 1.0 Transitional"Juan
+1. I don't know why this was -1. Anyway it should be noted that browser support is pretty much nil.Limner
Pretty sure Opera supports this.Upturned
@Limner it only works in XHTML. Doesn't work in make-believe XHTML sent as text/HTML.Lona
Eesh, not a fan of this. To me, the value of HTML is that everyone on the planet knows what it means (more or less), because we all use the same tags and attributes. I’m not sure why the class attribute isn”t enough extensibility.Nipping
Lack of browser support is annoying. It still seems useful - we could write a script to insert the extra text before sending it to the validatorDoorpost
H
28

We can assign base 64 encoded string as a source/href attribute of image, JavaScript,iframe,link

e.g.

<img alt="Embedded Image" width="297" height="246" 
  src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASkA..." />

div.image {
  width:297px;
  height:246px;
  background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASkA...);
}

<image>
  <title>An Image</title>
  <link>http://www.your.domain</link>
  <url>data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASkA...</url>
</image>

<link rel="stylesheet" type="text/css"
  href="data:text/css;base64,LyogKioqKiogVGVtcGxhdGUgKioq..." />

<script type="text/javascript"
  href="data:text/javascript;base64,dmFyIHNjT2JqMSA9IG5ldyBzY3Jv..."></script>

References

How can I construct images using HTML markup?

Binary File to Base64 Encoder / Translator

Hotze answered 5/6, 2009 at 4:58 Comment(1)
Sadly, IE < 8 doesn’t support this. You can however use MHTML instead for these browsers: phpied.com/mhtml-when-you-need-data-uris-in-ie7-and-underSaphra
F
26

I recently found out about the fieldset and label tags. As above, not hidden but useful for forms.

<fieldset> explanation

Example:

<form>
  <fieldset>
    <legend>Personalia:</legend>
    Name: <input type="text" size="30" /><br />
    Email: <input type="text" size="30" /><br />
    Date of birth: <input type="text" size="10" />
  </fieldset>
</form>
Forgo answered 5/6, 2009 at 4:58 Comment(6)
Please provide a sample use this.Cindy
Explanation: w3schools.com/TAGS/tag_fieldset.asp -- Example: w3schools.com/TAGS/tryit.asp?filename=tryhtml_fieldsetBrunhilda
Discovered fieldset from aspnet mvc sample page. ^^Paloma
Didn't know about this one. Heres the W3c spec: w3.org/TR/html401/interact/forms.html#h-17.10Ferric
Fieldsets and legends are great. A really nice way to mark up your forms.Bibliofilm
Fieldset is kind of flaky. Most browsers have major rendering hacks for them.Dordrecht
O
25

Most are also unaware of the fact that you can distinguish the form button pressed by just giving them a name/value pair. E.g.

<form action="process" method="post">
     ...
     <input type="submit" name="edit" value="Edit">
     <input type="submit" name="delete" value="Delete">
     <input type="submit" name="move_up" value="Move up">
     <input type="submit" name="move_up" value="Move down">
</form>

In the server side, the actual button pressed can then be obtained by just checking the presence of the request parameter associated with the button name. If it is not null, then the button was pressed.

I've seen a lot of unnecessary JS hacks/workarounds for that, e.g. changing the form action or changing a hidden input value beforehand depending on the button pressed. It's simply astonishing.

Also, I've seen almost as many JS hacks/workarounds to gather the checked ones of multiple checkboxes like as in table rows. On every select/check of a table row the JS would add the row index to some commaseparated value in a hidden input element which would then be splitted/parsed further in the server side. That's result of unawareness that you can give multiple input elements the same name but a different value and that you can still access them as an array in the server side. E.g.

<tr><td><input type="checkbox" name="rowid" value="1"></td><td> ... </td></tr>
<tr><td><input type="checkbox" name="rowid" value="2"></td><td> ... </td></tr>
<tr><td><input type="checkbox" name="rowid" value="3"></td><td> ... </td></tr>
...

The unawareness would give each checkbox a different name and omit the whole value attribute. In some JS-hack/workaround-free situations I've also seen some unnecessarily overwhelming magic in the server side code to distinguish the checked items.

Orta answered 5/6, 2009 at 4:58 Comment(12)
Keep in mind that most browsers implement a "feature" which submits the form if you press the enter key while inside a text input. You will find that each browser has its own interpretation of which button, if any, was "clicked" in this situation (unless there is exactly one button, in which case the major browsers actually agree)Moue
Normally the firstnext input or button of type="submit" in the tabindex order will be invoked. And yes, you have control over tabindex with help of the HTML tabindex attribute.Orta
Hey .. That's apparently another hidden feature of HTML :/ ;)Orta
If a form has multiple submit buttons, and the user clicks one, certain versions of Internet Explorer will cheerfully tell your server that they were all clicked. Wonderful.Disturbance
@detly: only if you use <button type="submit"> instead of <input type="submit"> :)Orta
...buuuuut doesn't IE6 also have problems with <input type="submit">? (My memory of this issue is hazy - I've long since convinced employers to not worry about IE compatibility for internal web apps, so it's not my problem any more. But I seem to recall some barrier to making this problem solvable in IE6.)Disturbance
That's not very i18n-friendly.Dordrecht
@zneak: then just give the buttons a different name and check if it is present as request parameter.Orta
@Orta I'm confused. Isn't your post exactly about not doing that?Dordrecht
@zneak: I understood that you was worrying about i18n-ability of button values? I don't see other i18n issues.Orta
@Orta Yes, I'm worried about the i18n-ability of button values, but changing button names kind of defeats the idea of using the same button name. :/Dordrecht
@zneak: I didn't mean to imply that you need to give them each the same name, but just that you can give them a name. Without a name you won't be able to distinguish the button pressed and hence a lot of ignorant developers would introduce horrible JS workarounds.Orta
R
25

<optgroup> is a great one that people often miss out on when doing segmented <select> lists.

<select>
  <optgroup label="North America">
    <option value='us'>United States</option>
    <option value='ca'>Canada</option>
  </optgroup>
  <optgroup label="Europe">
    <option value='fr'>France</option>
    <option value='ir'>Ireland</option>
  </optgroup>
</select>

is what you should be using instead of

<select>
  <option value=''>----North America----</option>
  <option value='us'>United States</option>
  <option value='ca'>Canada</option>
  <option value=''>----Europe----</option>
  <option value='fr'>France</option>
  <option value='ir'>Ireland</option>
</select>
Roturier answered 5/6, 2009 at 4:58 Comment(0)
F
25

You can use the object tag instead of an iframe to include another document in the page:

<object data="data/test.html" type="text/html" width="300" height="200">
  alt : <a href="data/test.html">test.html</a>
</object>
Ferrochromium answered 5/6, 2009 at 4:58 Comment(5)
Which ends up working almost exactly like an iframe except that it is less well supported and has fewer features.Juan
iframe is deprecated, hopefully we'll get better support soon,Discursive
iframe is not deprecated in HTML 5.Ferrochromium
Does it prevent XSS attacks from the embedded page?Caravaggio
I believe it uses SOP, same as with iframes.Ferrochromium
C
22

Colgroup tag.

<table width="100%">
    <colgroup>
        <col style="width:40%;" />
        <col style="width:60%;" />
    </colgroup>
    <thead>
        <tr>
            <td>Column 1<!--This column will have 40% width--></td>
            <td>Column 2<!--This column ill have 60% width--></td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Cell 1</td>
            <td>Cell 2</td>
        </tr>
    </tbody>
</table>
Chalaza answered 5/6, 2009 at 4:58 Comment(2)
In my experience, colgroup support is flaky at best.Limner
strikingly similar is WPF GridCindy
J
18

If the for attribute of a <label> tag isn't specified, it is implicitly set as the first child <input>, i.e.

<label>Alias: <input name="alias" id="alias"></label>

is equivalent to

<label for="alias">Alias:</label> <input name="alias" id="alias">
Jeanicejeanie answered 5/6, 2009 at 4:58 Comment(4)
But this enjoys less browser support than the for attributeJuan
@Moue — Do you have any documentation to back that up? I don't think I've ever seen a browser not support this usage. I've personally tested in IE6/7, FF2/3, Safari 3, and Chrome 1/2. I haven't tested myself in Opera, but I'd be very surprised if it didn't work. This behavior is part of the original HTML 4.0 spec, first published more than eleven years ago: w3.org/TR/1998/REC-html40-19980424/interact/forms.html#adef-forAdamite
Also, it's not valid to put an input inside of a label, and DOH you didn't close your input tag in either example!Kleist
You are wrong on both counts: this is valid practice, and the end tag is forbidden of input elements.Jeanicejeanie
P
15

Button as link, no JavaScript:

You can put any kind of file in the form action, and you have a button that acts as a link. No need to use onclick events or such. You can even open-up the file in a new window by sticking a "target" in the form. I didn't see that technique in application much.

Replace this

<a href="myfile.pdf" target="_blank">Download file</a>

with this:

<form method="get" action="myfile.pdf" target="_blank">
    <input type="submit" value="Download file">
</form>
Pesthouse answered 5/6, 2009 at 4:58 Comment(7)
Button won't have "Save file as" option, which may be needed by users who don't like Adobe Acrobat taking over their browser.Lona
It will behave with default browser behavior when accessing PDF file. It could be an HTML file, a word file, a zip file, or anything else you want.Pesthouse
In what situation does a anchor tag require an onclick event? and why would 3 lines of html be better than 1? Is the idea that you CAN have a button instead of a link, so it's nice and button like? Even though I sound cranky about this, I actually have a page that uses buttons instead of links because the file gets created dynamically when the user requests it, so I didn't want a link to: blah.php?stuff="userdata" Even though I could have gone that route, I didn't want to risk the filename having the file-generating script as the name instead of the filename that the script gives the file.Kleist
As a side note: in IE8, when you hover over the button you can see the target in the status bar. Firefox 3 unfortunately doesn't show it :(Amalgamate
Why not just style the <a> tag like a button? This seems like a lot of junk in your markup.Nut
@Nut some web applications want to look the same as the OS. E.g. an ugly button when the user uses Windows, and a beautiful button when the user uses Mac OS X.Killoran
Yeah fair enough, those proprietary safari buttons are so annoying.Nut
C
13

Simplest way to refresh the page in X seconds - META Refresh

<meta http-equiv="refresh" content="600">

The value in content signifies the seconds after which you want the page to refresh.
[Edit]

<meta http-equiv="refresh" content="0; url=foobar.example/index.html">

To do a simple redirect!
(Thanks @rlb)

Cindy answered 5/6, 2009 at 4:58 Comment(14)
Of course, working out which elements need refreshing and then updating them via AJAX results in a much nicer user experience...Chasseur
META refresh doesn't really do anything good in pages where there's also some king of user form activity, because it can interrupt user's form fill-in and discard all the work. I think there's rarely an occasion where these kind of refreshes would be best. It's just the easy way out normally.Reddish
Well all features as usual has to be used wisely.Cindy
/me hates pages that refresh like that... should be banned =/Extrauterine
Nothing wrong with this, as long as you put it under the user's control (I had an app that provided a user-selectible "auto-refresh" option, turned off by default).Tycoon
This can also be useful if set to a little less than the session timeout to notify the user that his session has timed-out and was removed.Bricebriceno
I only find this useful if a page/resource was removed and the webmaster/author wants to explain why I'm suddenly off to another URL, without making me click on a new link.Boong
@Svish, this is useful in sports websites. The score of a game currently in progress can be updated using this.Novocaine
Also super simple way to do a redirect. ; ) <meta HTTP-EQUIV="REFRESH" content="0; url=foobar.com/index.html">Kamalakamaria
Short timeouts break back button.Lona
META REFRESH also causes the browser to perform cache validation on even fresh resources, which incurs a performance cost.Rett
<meta HTTP-EQUIV="REFRESH" content="0; url=foobar.com/index.html"> is likely to cause issues with browser histories - trying to back through a refresh of less than about 3s is difficult and you will just irritate usersMold
This should be hidden in a box, and thrown out to sea.Nut
OMG! CHOOSE: REQUIRE THE USER TO RELOAD OR USE AJAX! Or simply read articles on usability ^^Killoran
C
12

<html>, <head> and <body> tags are optional. If you omit them, they will be silently inserted by the parser in appropriate places. It's perfectly valid to do so in HTML (just like implied <tbody>).

HTML in theory is an SGML application. This is probably the shortest valid HTML 4 document:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<title//<p/

The above doesn't work anywhere except W3C Validator. However shortest valid HTML5 text/html document works everywhere:

<!DOCTYPE html><title></title>
Confidant answered 5/6, 2009 at 4:58 Comment(5)
You should be careful what you advertise. The above code will pass validation with 4 warnings at the w3c validator, but the DocType is HTML 4.0. It is pretty neat that HTML 4 is decendant of SGML and therefore maintains this loose validation standard, but if you change that DTD to XHTML 1.0 STRICT, it gets 15 errors, which is almost equal to the number of characters. XHTML was developed because HTML was so lazy (and thus unsecure) so we don't want to take advantage of that anymore.Kleist
If you change DOCTYPE of HTML/SGML document to XHTML/XML you will get nonsensical mix. That's quite obvious and I'm not sure why you're pointing that out.Lona
This example might, technically, be valid HTML 4, but browsers do not support that abbreviated SGML syntax. The following is the shortest valid HTML 5 document, which browsers do actually support: <!DOCTYPE html><title></title>Sprightly
Any idea how compatible is it to leave out head/body, not just from a validation perspective?Aslant
@kibibu: Browsers don't have problems with this. Old versions of Opera used to omit <head> in DOM sometimes, but head content was in DOM and worked anyway. The biggest problem I've found is that OpenID clients require <head> to be explicitly present.Lona
E
11

The lang attribute is not very well known but very useful. The attribute is used to identify the language of the content in either the whole document or in a single element. Langage codes are given in ISO 2-letter Language code (i.e. 'en' for English, 'fr' for French).

It's useful for browsers who can adjust their display of quotation marks, etc. Screen readers also benefit from the lang attribute as well as search engines.

Sitepoint has some nice explanation of the lang attribute.

Examples

Specify the language to be English for the whole document, unless overridden by another lang attribute on a lower level in the DOM.

<html lang="en">

Specify the language in the following paragraph to be Swedish.

<p lang="sv">Ät din morgongröt och bli stor och stark!</p>
Euphorbia answered 5/6, 2009 at 4:58 Comment(0)
T
10

The "!DOCTYPE" declaration. Don't think it's a hidden feature, but it seems it's not well known but very useful.

e.g.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
    "http://www.w3.org/TR/html4/strict.dtd">
Tureen answered 5/6, 2009 at 4:58 Comment(6)
And not to mention "mandatory for most current markup languages and without one it is impossible to reliably validate a document"... validator.w3.org/docs/help.html#faq-doctypeExtrauterine
I don't think this is "not well known" anymore. In the time between IE 6 and IE 7, doctype use went from ~1% to >50%.Limner
@Limner Most IDE includes this tag that's why its use increased. I think this tag is not well known.Cupola
And using a strict doctype fixes 95% of browser inconsistencies.Muoimuon
Part of the standart and used by 99% of the developers out there doesn't sound like "hidden feature".Richie
HTML5 makes the doctype declaration easy to remember and type, for all of us using regular text editors. It's just <!doctype html>. That is reason alone to start using HTML5. :)Lohrman
D
6

That's only lowly related to HTML, but very few people know it.

People abuse the <meta> tag with the http-equiv attribute:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta http-equiv="Refresh" content="5; url=somewhere/"/>

However, many developers don't even know what this does. The http-equiv attribute means that the tag is meant to replace an HTTP header in cases where you aren't in control of them. Therefore, most work done through http-equiv should be done on the server side.

Besides, it's not as powerful: several properties of a document can't be changed through <meta> tags. Content-Type in a <meta> tag can tell the browser to use a certain charset, but most will ignore any change to the MIME type of the document (so you can't make a text/html document an application/xhtml+xml one that way).

Both tags from the example should be replaced by these simple calls:

<?php
header('Content-Type: text/html; charset=UTF-8');
header('Refresh: 5; url=somewhere/');
?>

It's bound to work on any HTTP-compliant browser (which means, pretty much every single browser).

Dordrecht answered 5/6, 2009 at 4:58 Comment(3)
It should be noted that <meta http-equiv="Refresh" content="5; url=foo"> actually triggers a full page refresh in IE (including all cached assets). Can haz performance nightmare plx? blogs.msdn.com/b/ieinternals/archive/2010/05/13/…Saphra
The W3C validator recommends including encoding in the meta element so users can save the web page to the local file system.Aslant
@kibibu: That's quite possible, actually. I've been doing XHTML documents rather than HTML documents since long ago (I gave up on Internet Explorer about 3 years ago), so I put that information in the <?xml?> declaration at the top of the document: <?xml version="1.0" encoding="UTF-8"?>Dordrecht
W
5

Superscript with <sup> x </sup>

Wryneck answered 5/6, 2009 at 4:58 Comment(0)
K
3

My favorite hidden feature was already mentioned, which is the "base" tag. Very handy for when you have a chunk of code that has relative URLs and suddenly they all move but your page doesn't.

But one that wasn't mentioned is the list header tag <lh>. It probably wasn't mentioned because it is considered "depreciated" but most browsers still support it. I don't know why it was phased out, nearly every unordered list I make could use a header, and it feels icky just dropping a h3 tag, and it feels just incorrect to make the first list item the title of the list.

Kleist answered 5/6, 2009 at 4:58 Comment(2)
you should look into the <dt>, <dl> and <dd> tags - definition lists are also rather obscure markup, but very useful.Mold
I hadn't heard of the <lh> element before. I like the point you make of its semantic importance. To bad it's deprecated. :(Licit
S
3

A form can be submitted when you press the Enter key on a text input only if there is a submit button in the form. Try it here. It won't work if you don't change the type of the button to "submit".

Shovel answered 5/6, 2009 at 4:58 Comment(1)
This depends on the browser you are using. In HTML 2, a form containg just a text input SHOULD be submitted with enter. alanflavell.org.uk/www/formquestion.htmlJuan
T
2

Special characters for math, greek,... not known very well

Tureen answered 5/6, 2009 at 4:58 Comment(9)
And not really needed in a world with UTF-8Juan
Not really needed, but I for one prefer &pi; to &#960;Salver
I said UTF-8 not numeric character references. i.e. πJuan
@Moue Dorward: sometimes, it's easier to look up the entity on a list than it is to get your keyboard to print ł or Æ, for example.Softfinned
If you've looked up the entity on a list, then you can either transcribe the entity, copy and paste the entity or ... just copy and paste the character itself :)Juan
Reading the source code back afterwards is rather easier if you have the actual characters in it too.Juan
@Moue Dorward: but π is just a Greek character (as are all[most] other 'numeric character references')Mold
@Mold — No, character references are (to various degrees) obtuse bits of ASCII that can be translated into characters given software, a look up table or being able to remember particular ones. Actual characters are (as mentioned above) easier to read.Juan
@David: I prefer to type the characters if I can (yay for a Compose key) but if I can't, having the entity form of all of them is rather convenient and much better than nothing. It's also safer when the page has to go through non-8bit-safe transfer. (Thankfully rare nowadays!)Tybie
M
0

Definition lists:

<dl>
  <dt>Some Term</dt>
  <dd>Some description</dd>
  <dd>Some other description</dd>

  <dt>Another Word/Phrase</dt>
  <dd>Some description</dd>
</dl>

I've also retasked this for form layouts and navigation menus for various sites.

Mold answered 5/6, 2009 at 4:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.