在 HTML 标记中添加宽度边界的简洁方法
采用以下标记:
<!DOCTYPE html>
<html>
<head>
<title>My test for StackOverflow</title>
</head>
<body>
<header>
<span>LOGO_WOULD_BE_HERE</span>
</header>
<article>
<h1>The title of my page</h1>
<p>Blah blah blah</p>
</article>
<footer>
<p>Copyright (c) 2011 The World.</p>
</footer>
</body>
</html>
这一切都很好,干净且语义 - 但是,想象一下主要的包装块元素需要有一个占据页面整个宽度的背景,并且您的内容需要在宽度边界内(例如最小宽度:x;最大宽度:y 的容器以允许弹性)。
“简单”的方法就是创建一个宽度边界类,将所有内容包装在其中,例如:
<header>
<div class="width-boundary">
<h1>The title of my page</h1>
<p>Blah blah blah</p>
</div>
</header>
使用类似于以下的 CSS:
.width-boundary { min-width: 400px; max-width: 960px; margin: 0 auto; }
但这是一个丑陋的解决方案,因为您最终会在您的漂亮页面上得到一堆包装器新标记。
我很想听到对此有任何优雅的解决方案 - 尽可能少地添加额外的标记,并且添加的任何内容都应该是语义的。
Take the following markup:
<!DOCTYPE html>
<html>
<head>
<title>My test for StackOverflow</title>
</head>
<body>
<header>
<span>LOGO_WOULD_BE_HERE</span>
</header>
<article>
<h1>The title of my page</h1>
<p>Blah blah blah</p>
</article>
<footer>
<p>Copyright (c) 2011 The World.</p>
</footer>
</body>
</html>
This is all fine, clean and semantic - however, imagine that the main, wrapping block elements need to have a background which takes up the entire width of the page, and your content needs to be within a width boundary (for example a container of min-width: x; max-width: y to allow elasticity).
The 'easy' way would simply be to create a width-boundary class, that you wrap everything in, for example:
<header>
<div class="width-boundary">
<h1>The title of my page</h1>
<p>Blah blah blah</p>
</div>
</header>
With CSS similar to:
.width-boundary { min-width: 400px; max-width: 960px; margin: 0 auto; }
This is an ugly solution though, as you end up with a bunch of wrappers all over your nice new markup.
I'm keen to hear of any elegant solutions to this - with as little additional as markup as possible and whatever is added should be semantic.
Here is a playground I've setup on JSFiddle.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您非常关心语义,可以对标记进行一些改进:
将宽度约束应用于
#content >改为article
:这样,您就可以完全取消
和
width-boundary
类。If you're that concerned about semantics, here's a little improvement to your markup:
Apply the width constraints to
#content > article
instead:This way, you can do away with the
<div>
and thewidth-boundary
class altogether.你不能将类添加到文章标签中吗?
它消除了对额外 div 包装的需要
couldn't you just add the class to the article tag?
it removes the need for the extra div wrapper