Html 做 CSS Wrapper 的正确方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5275410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:17:41  来源:igfitidea点击:

What is the correct way to do a CSS Wrapper?

htmlcss

提问by RSM

I have heard a lot of my friends talk about using wrappers in CSS to center the "main" part of a website.

我听到很多朋友谈论在 CSS 中使用包装器来使网站的“主要”部分居中。

Is this the best way to accomplish this? What is best practice? Are there other ways?

这是实现这一目标的最佳方式吗?什么是最佳实践?还有其他方法吗?

回答by Aron Rotteveel

Most basic example (live example here):

最基本的例子(这里是现场例子):

CSS:

CSS:

#wrapper {
    width: 500px;
    margin: 0 auto;
}

HTML:

HTML:

<body>
    <div id="wrapper">
        Piece of text inside a 500px width div centered on the page
    </div>
</body>

How the principle works:

原理如何运作:

Create your wrapper and assign it a certain width. Then apply an automatic horizontal margin to it by using margin: 0 auto;or margin-left: auto; margin-right: auto;. The automatic margins make sure your element is centered.

创建您的包装器并为其分配一定的宽度。然后使用margin: 0 auto;或为其应用自动水平边距margin-left: auto; margin-right: auto;。自动边距确保您的元素居中。

回答by Kaloyan Kosev

The best way to do it depends on your specific use-case.

最好的方法取决于您的特定用例。

However, if we speak for the general best practicesfor implementing a CSS Wrapper, here is my proposal: introduce an additional <div>element with the following class:

但是,如果我们谈论实现 CSS Wrapper的一般最佳实践,这是我的建议:引入<div>具有以下类的附加元素

/**
 * 1. Center the content. Yes, that's a bit opinionated.
 * 2. Use `max-width` instead `width`
 * 3. Add padding on the sides.
 */
.wrapper {
    margin-right: auto; /* 1 */
    margin-left:  auto; /* 1 */

    max-width: 960px; /* 2 */

    padding-right: 10px; /* 3 */
    padding-left:  10px; /* 3 */
}

... for those of you, who want to understand why, here are the 4 big reasons I see:

...对于那些想了解原因的人,以下是我看到的 4 个重要原因:

1. Use max-widthinstead width

1.max-width改用width

In the answer currently acceptedAron says width. I disagree and I propose max-widthinstead.

目前接受答案中,Aron 说width。我不同意,我建议max-width

Setting the widthof a block-level element will prevent it from stretching out to the edges of its container. Therefore, the Wrapper element will take up the specified width. The problem occurs when the browser window is smaller than the width of the element. The browser then adds a horizontal scrollbar to the page.

设置width块级元素的 将防止它延伸到其容器的边缘。因此,Wrapper 元素将占据指定的宽度。当浏览器窗口小于元素的宽度时会出现问题。然后浏览器向页面添加一个水平滚动条。

Using max-width instead, in this situation, will improve the browser's handling of small windows. This is important when making a site usable on small devices. Here's a good example showcasing the problem:

在这种情况下,改用 max-width 将改善浏览器对小窗口的处理。这在使网站可在小型设备上使用时很重要。这是一个很好的例子来展示这个问题:

/**
 * The problem with this one occurs
 * when the browser window is smaller than 960px.
 * The browser then adds a horizontal scrollbar to the page.
 */
.width {
    width: 960px;
    margin-left: auto;
    margin-right: auto;
    border: 3px solid #73AD21;
}

/**
 * Using max-width instead, in this situation,
 * will improve the browser's handling of small windows.
 * This is important when making a site usable on small devices.
 */
.max-width {
    max-width: 960px;
    margin-left: auto;
    margin-right: auto;
    border: 3px solid #73AD21;
}

/**
 * Credits for the tip: W3Schools
 * https://www.w3schools.com/css/css_max-width.asp
 */
<div class="width">This div element has width: 960px;</div>
<br />

<div class="max-width">This div element has max-width: 960px;</div>

So in terms of Responsiveness, is seems like max-widthis the better choice!-

所以就响应能力而言,似乎max-width是更好的选择!-



2. Add Padding on the Sides

2.在侧面添加填充

I've seen a lot of developers still forget one edge case. Let's say we have a Wrapper with max-widthset to 980px. The edge case appears when the user's device screen width is exactly 980px. The content then will exactly glue to the edges of the screen with not any breathing space left.

我见过很多开发人员仍然忘记了一个边缘情况。假设我们有一个max-width设置为 980px的 Wrapper 。当用户的设备屏幕宽度正好是 980 像素时,就会出现边缘情况。然后内容将完全粘在屏幕的边缘,没有留下任何喘息空间。

Generally, we'd want to have a bit of padding on the sides. That's why if I need to implement a Wrapper with a total width of 980px, I'd do it like so:

通常,我们希望在侧面有一些填充。这就是为什么如果我需要实现一个总宽度为 980px 的 Wrapper,我会这样做:

.wrapper {
   max-width: 960px; /** 20px smaller, to fit the paddings on the sides */

   padding-right: 10px;
   padding-left:  10px;

   /** ... omitted for brevity */
}

Therefore, that's why adding padding-leftand padding-rightto your Wrapper might be a good idea, especially on mobile.

因此,这就是为什么将padding-left和添加padding-right到您的 Wrapper 可能是一个好主意,尤其是在移动设备上。



3. Use a <div>Instead of a <section>

3. 使用 a<div>而不是 a<section>

By definition, the Wrapper has no semantic meaning. It simply holds all visual elements and content on the page. It's just a generic container. Therefore, in terms of semantics, <div>is the best choice.

根据定义,Wrapper 没有语义意义。它只是保存页面上的所有视觉元素和内容。它只是一个通用的容器。因此,就语义而言, <div>是最好的选择。

One might wonder if maybe a <section>element could fit this purpose. However, here's what the W3C spec says:

人们可能想知道某个<section>元素是否适合这一目的。但是,这是 W3C 规范所说的:

The element is not a generic container element. When an element is needed only for styling purposes or as a convenience for scripting, authors are encouraged to use the div element instead. A general rule is that the section element is appropriate only if the element's contents would be listed explicitly in the document's outline.

该元素不是通用容器元素。当一个元素仅用于样式目的或方便脚本编写时,鼓励作者使用 div 元素代替。一般规则是,仅当元素的内容将在文档的大纲中明确列出时,section 元素才是合适的。

The <section>element carries it's own semantics. It represents a thematic grouping of content. The theme of each section should be identified, typically by including a heading (h1-h6 element) as a child of the section element.

<section>元素携带它自己的语义。它代表内容的主题分组。应确定每个部分的主题,通常通过将标题(h1-h6 元素)作为该部分元素的子元素来确定。

Examples of sections would be chapters, the various tabbed pages in a tabbed dialog box, or the numbered sections of a thesis. A Web site's home page could be split into sections for an introduction, news items, and contact information.

部分的示例包括章节、选项卡式对话框中的各种选项卡式页面或论文的编号部分。一个网站的主页可以分成几个部分,分别是介绍、新闻项目和联系信息。

It might not seem very obvious at first sight, but yes! The plain old <div>fits best for a Wrapper!

乍一看可能不是很明显,但是是的!简单的旧<div>最适合包装器!



4. Using the <body>Tag vs. Using an Additional <div>

4. 使用<body>标签与使用附加标签<div>

Here's a related question. Yes, there are some instances where you could simply use the <body>element as a wrapper. However, I wouldn't recommend you to do so, simply due to flexibility and resilience to changes.

这是一个相关的问题。是的,在某些情况下,您可以简单地将<body>元素用作包装器。但是,我不建议您这样做,因为它具有灵活性和适应变化的能力。

Here's an use-case that illustrates a possible issue: Imagine if on a later stage of the project you need to enforce a footer to "stick" to the end of the document (bottom of the viewport when the document is short). Even if you can use the most modern way to do it - with Flexbox, I guess you need an additional Wrapper <div>.

这是一个用例,它说明了一个可能的问题:想象一下,如果在项目的后期阶段,您需要强制页脚“粘”到文档的末尾(文档很短时的视口底部)。即使您可以使用最现代的方式来做到这一点 -使用 Flexbox,我猜您还需要一个额外的 Wrapper <div>

I would conclude it is still best practice to have an additional <div>for implementing a CSS Wrapper. This way if spec requirements change later on you don't have to add the Wrapper later and deal with moving the styles around a lot. After all, we're only talking about 1 extra DOM element.

我的结论是,<div>为实现 CSS Wrapper增加一个额外的内容仍然是最佳实践。这样,如果以后规范要求发生变化,您就不必稍后添加 Wrapper 并处理大量移动样式。毕竟,我们只是在讨论 1 个额外的 DOM 元素。

回答by AlanG

You don't need a wrapper, just use the body as the wrapper.

您不需要包装器,只需将主体用作包装器即可。

CSS:

CSS:

body {
    margin:0 auto;
    width:200px;
}

HTML:

HTML:

<body>
    <p>some content</p>
<body>

回答by Hussein

<div class="wrapper">test test test</div>

.wrapper{
    width:100px;
    height:100px;
    margin:0 auto;
}

Check working example at http://jsfiddle.net/8wpYV/

http://jsfiddle.net/8wpYV/检查工作示例

回答by wsanville

The easiest way is to have a "wrapper" divelement with a widthset, and a left and right margin of auto.

最简单的方法是拥有一个div带有width集合的“包装器”元素,并且左右边距为auto.

Sample markup:

示例标记:

<!doctype html>
<html>
<head>
    <title></title>
    <style type="text/css">
        .wrapper { width: 960px; margin: 0 auto; background-color: #cccccc; }
        body { margin: 0; padding: 0 }
    </style>
</head>
<body>
    <div class="wrapper">
        your content...
    </div>
</body>
</html>

回答by FelipeAls

Are there other ways?

还有其他方法吗?

Negative marginswere also used for horizontal (and vertical!) centering but there are quite a few drawbacks when you resize the window browser: no window slider; the content can't be seen anymore if the size of the window browser is too small.
No surprise as it uses absolute positioning, a beast never completely tamed!

负边距也用于水平(和垂直!)居中,但在调整窗口浏览器大小时有很多缺点:没有窗口滑块;如果窗口浏览器的大小太小,则无法再看到内容。
毫不奇怪,因为它使用绝对定位,从未完全驯服的野兽!

Example: http://bluerobot.com/web/css/center2.html

示例:http: //bluerobot.com/web/css/center2.html

So that was only FYI as you asked for it, margin: 0 auto;is a better solution.

所以这只是你要求的仅供参考,margin: 0 auto;是一个更好的解决方案。

回答by Chris Moschini

Centering content has so many avenues that it can't really be explored in a single answer. If you would like to explore them, CSS Zen Garden is an enjoyable-if-old resourceexploring the many, many ways to layout content in a way even old browsers will tolerate.

以内容为中心的途径太多了,无法在一个答案中真正探索。如果您想探索它们,CSS Zen Garden 是一个令人愉快的旧资源,它探索了许多以一种甚至旧浏览器都可以容忍的方式来布局内容的方法。

The correct way, if you don't have any mitigating requirements, is to just apply margin: autoto the sides, and a width. If your page has no content that needs to go outside those margins, just apply it to the body:

如果您没有任何缓解要求,正确的方法是仅适用margin: auto于侧面,并且width. 如果您的页面没有需要超出这些边距的内容,只需将其应用于正文:

body {
  padding: 0;
  margin: 15px auto;
  width: 500px;
}

https://jsfiddle.net/b9chris/62wgq8nk/

https://jsfiddle.net/b9chris/62wgq8nk/

So here we've got a 500px wide set of content centered at all* sizes. The padding 0 is to deal with some browsers that like to apply some default padding and throw us off a bit. In the example I do wrap the content in an articletag to be nice to Screen Readers, Pocket, etc so for example the blind can jump past the nav you likely have (which should be in nav) and straight to the content.

所以这里我们有一个 500px 宽的内容集,以所有*大小为中心。padding 0 是为了处理一些浏览器喜欢应用一些默认的 padding 并让我们有点失望。在示例中,我确实将内容包装在一个article标签中,以便于屏幕阅读器、Pocket 等使用,例如盲人可以跳过您可能拥有的导航(应该在 中nav)并直接进入内容。

I say all* because below 500px this will mess up - we're not being Responsive. To get Responsive, you could just use Bootstrap etc, but building it yourself you use a Media Query like:

我说全部*是因为低于 500px 这会搞砸 - 我们没有响应。要获得响应式,您可以只使用 Bootstrap 等,但自己构建它您使用媒体查询,例如:

body {
  padding: 0;

  margin: 15px;
  @media (min-width: 500px) {
    margin: 15px auto;
    width: 500px;
  }
}

Note that this is SCSS/SASS syntax - if you're using plain CSS, it's inverted:

请注意,这是 SCSS/SASS 语法 - 如果您使用的是纯 CSS,则将其反转:

body {
  padding: 0;  
  margin: 15px;
}

@media (min-width: 500px) {
  body {
    margin: 15px auto;
    width: 500px;
  }
}

https://jsfiddle.net/b9chris/62wgq8nk/6/

https://jsfiddle.net/b9chris/62wgq8nk/6/

It's common however to want to center just one chunk of a page, so let's apply this to only the article tag in a final example.

然而,通常只想将页面的一个块居中,因此让我们在最后一个示例中仅将其应用于文章标签。

body {
  padding: 0;
  margin: 0;
}

nav {
  width: 100%;
  box-sizing: border-box;
  padding: 15px;
}

article {
  margin: 15px;
  @media (min-width: 500px) {
    margin: 15px auto;
    width: 500px;
  }
}

https://jsfiddle.net/b9chris/62wgq8nk/17/

https://jsfiddle.net/b9chris/62wgq8nk/17/

Note that this final example also uses CSS Flexboxin the nav, which is also one of the newer ways you could center things. So, that's fun.

请注意,这最后一个示例还在导航中使用了CSS Flexbox,这也是您可以将事物居中的新方法之一。所以,这很有趣。

But, there are special circumstances where you need to use other approaches to center content, and each of those is probably worth its own question (many of them already asked and answered here on this site).

但是,在某些特殊情况下,您需要使用其他方法来使内容居中,而这些方法中的每一个都可能值得提出自己的问题(其中许多已经在本网站上提出并回答了)。

回答by Garrett Michael Gritz Stelly

a "wrapper" is just a term for some element that encapsulates all other visual elements on the page. The bodytag seems to fit the bill, but you would be at the mercy of the browser to determine what displays beneath that if you adjust the max-width.

“包装器”只是一些元素的术语,它封装了页面上的所有其他视觉元素。该body标签似乎符合要求,但如果您调整max-width.

Instead, we use divbecause it acts as a simple container that does not break. the main, header, footer, and sectiontags in HTML5 are just divelements named appropriately. It seems that there could (or should) be a wrappertag because of this trend, but you may use whichever method of wrapping you find most suitable for your situation. through classes, ids and css, you can use a spantag in a very similar way.

相反,我们使用div它是因为它充当了一个不会损坏的简单容器。在mainheaderfooter,和section在HTML5标记只是div适当命名的元素。wrapper由于这种趋势,似乎可能(或应该)有一个标签,但您可以使用最适合您情况的包装方法。通过类、ID 和 css,您可以span以非常相似的方式使用标签。

There are a lot of HTML element tags that we do not use often or possibly even know about. Doing some research would show you what can be done with pure HTML.

有很多 HTML 元素标签我们不经常使用,甚至可能都不知道。做一些研究会告诉你可以用纯 HTML 做什么。

回答by Joe

/******************
Fit the body to the edges of the screen
******************/    

body {
         margin:0;
         padding:0;
    }

header {
     background:black;
     width:100%;
}

.header {
     height:200px;
}

nav {
     width:100%;
     background:lightseagreen;
}

.nav {
     padding:0;
     margin:0;
}

.nav a {
     padding:10px;
     font-family:tahoma;
     font-size:12pt;
     color:white;
}

/******************
Centered wrapper, all other content divs will go inside this and will never exceed the width of 960px.
******************/

    .wrapper {
         width:960px;
         max-width:100%;
         margin:0 auto;
    }



<!-------- Start HTML ---------->

    <body>

<header>

    <div id="header" class="wrapper">

    </div>

</header>

<nav>

     <div id="nav" class="wrapper">

     </div>

</nav>



    </body>