简体   繁体   中英

<span>/<div> shorthand for css - is this legit?

If I create an HTML element:

sc {
    font-variant: small-caps;
}

and apply it like this:

I want to display <sc>this text</sc> in small-caps.

it works as expected (except in IE, of course.) It becomes shorthand for

.sc {
    font-variant: small-caps;
}
I want to display <span class='sc'>this text</span> in small-caps.

Is this intended/documented behavior? Is there a name for it?

XHTML (and XML on which it is based) is designed to let you add custom elements in a similar fashion, but instead using a custom XML namespace with your element names. Then you can either use CSS to style those elements directly, or use XSLT to transform them into real HTML elements. This is why (or at least one reason why) standards-compliant browsers are OK handling otherwise non-standard elements in the DOM.

In HTML 4 and older, it's always invalid to sprinkle your own non-standard elements on (not sure about HTML5's extensibility).

Either way, however, IE doesn't automatically know about the custom elements in the DOM, so you need to use document.createElement() to create them before the DOM finishes loading.

It works in IE too if you add document.createElement('sc'); and it is "legit". This is what the HTML5 shiv does.

Unlike most javascript functions however, this has to be called before the actual use of the element, not after page/DOM load.

While it will work, it is not valid unless you are using XHTML (real XHTML, with the right Content-Type and all... not harmful XHTML ) and a namespace:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html 
      PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>&lt;span&gt; shorthand for css - is this legit?</title>
  </head>
  <body>

    <h1>Custom tags in XHTML</h1>

    I want to display
    <sc xmlns="http://le-dorfier.example.com">
      this text
    </sc>
    in small-caps.

  </body>
</html>

For more info check out the Namespace Crash Course on MDN docs.

Unrecognised elements are handled and will WORK in all modern browsers. However it should show up as invalid markup.

In older versions of ie you can't style unrecognised elements - you can just do document.createElement('sc') in JavaScript though.

Hypothetically, if you have not specified an HTML doc type and are treating your document as an XML document, you could attach a stylesheet to it to define the visual behavior of any tag you want.

See http://csszengarden.com/ for more information on this.

Essentially, you could have a bare XML document with a CSS stylesheet attached to it that would lay it out as you see fit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM