开发者

Workaround for unrecognized <section> tags in older browsers

I have a pair of nested section tags to set the width of my content, but am having problems with browsers (or versions of browsers) that don't recognize the tag: they're just allowing the content to fill the entire width of the parent container.

My code looks essentially like this:

<body>
    <section style="min-width:800px">
        <section style="width:500px">
            <p>Bunch of Text Here That Forms The Content</p>
        </section>
    </section>
</body>

Now in b开发者_JS百科rowsers that don't recognize the <section> tag, the content in the inner <section> behaves as if the tag does not exist, and the content simply fills the width of the page. Any idea what I can do about it?


If you don't mind your site's design and layout depending on JavaScript for older browsers (mainly IE versions 6-8), you can use the HTML5 JavaScript shim for IE or Modernizr:

<head>
    <meta charset="utf-8" />
    <title>Stack Overflow Rocks!</title>

    <link rel="stylesheet" href="/path/to/file.css" media="all" />

    <!--[if lt IE 9]>
        <script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
</head>

To use this script, it must be included before the element (i.e. in the <head>) but doesn't matter if it appears before or after any CSS. However, for the sake of performance, it's preferable to include any CSS before this script.

A clever and somewhat creative approach that doesn't rely on JavaScript is to insert an element that IE/Win 6-8 understands, (such as a plain old <div>) inside of the semantic HTML5 elements:

<aside>
    <div id="sidebar">
        <!-- Business as Usual Here -->
        ...
    </div>
</aside>

You can then apply your CSS using either the ID (for older browsers) or the HTML5 element (for modern browsers):

aside,
#sidebar {
    ...
}

While this approach adds an extra set of tags for each HTML5 element — and arguably isn't a pure as the native HTML5 method — it doesn't depend on JavaScript and your site's layout can look the same with or without JavaScript enabled.


For further reading about HTML5 elements and IE/Win, see The Story of the HTML5 Shiv.


Most browsers treat unknown tags as if they had display: inline applied to them. You’ll want to apply display: block to <section> (and other block-level HTML5 tags, if you plan to use them) in your stylesheet. (Reset stylesheets, like Eric Meyer’s, often take care of this for you.)

Older versions of IE, in contrast, won’t allow you to style tags at all if they don’t know about them (e.g. IE 6 was not aware of the <abbr> tag even though it was in the HTML 4 spec), unless you create that an instance of the tag via JavaScript. That’s what the HTML5 shiv does.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜