【问题标题】:What is the use of .container div in this W3Schools example?这个 W3Schools 示例中 .container div 的用途是什么?
【发布时间】:2016-04-05 15:20:58
【问题描述】:

我试图了解 CSS layout horizontal alignment 并遇到了 this 示例

body {
  margin: 0;
  padding: 0;
}
.container {
  position: relative;
  width: 100%;
}
.right {
  position: absolute;
  right: 0px;
  width: 300px;
  background-color: #b0e0e6;
}
<div class="container">
  <div class="right">
    <p><b>Note: </b>When aligning using the position property, always include the !DOCTYPE declaration! If missing, it can produce strange results in IE browsers.</p>
  </div>
</div>

如果我们删除.container 类或整个div.container,则ChromeIE 10IE 8 上的效果

这个.container在这个例子中的作用是什么?

【问题讨论】:

  • 这就是它所说的......有些人说“包装器”......它是为了更容易控制内部元素。我同意,如果你有一个元素,类right,它似乎不需要在那里..但是假设你希望整个页面占用80%的显示宽度,然后浮动您的子元素right -- 容器是完成此任务的最简单方法。所以你的例子本身不需要它..但它是;-)
  • @Zak 小提琴可能有助于更好地理解!
  • 啊。以下 w3schools 示例的危险.... 从形式上讲,它没有效果,因为 .container 元素的右内容框边缘与初始包含块的右边缘重合。但不要指望 w3schools 会解释(甚至理解它)。

标签: html css layout css-position


【解决方案1】:

这就是它所说的“容器”......有些人说“包装器”......它是为了更容易控制内部元素。我同意,如果你有一个元素,并且类正确,它似乎不需要在那里.. 但是假设你希望整个页面占据 80% 的显示宽度,然后浮动你的孩子element right——容器是完成此任务的最简单方法。所以你的例子本身不需要它..但它是;-)

.container {
position: relative;
border: 1px #00FF00 solid;
width: 80%;
height:500px;
}

.right {
position: absolute;
right: 0px;
background-color: #b0e0e6;
border: 1px #FF0000 solid;
height: 50px;
width: 50px;
}

Fiddle

【讨论】:

  • 那么,div.container 的角色不允许div.right 离开div.container,这就是重点吗?同样没有position: absolute;div.right 会粘在左边缘。
  • 正确 .. 和 .. 正确 .. 它会粘在左边缘,因为周围的 DIVrelative ... 和 absolute 没有任何基础它的“绝对性”周围没有relative div。我建议您阅读有关relativeabsolutefloating 的更多信息..
猜你喜欢
  • 1970-01-01
  • 2013-12-10
  • 1970-01-01
  • 2016-11-25
  • 2019-07-31
  • 1970-01-01
  • 2012-12-02
  • 1970-01-01
  • 2021-04-02
相关资源
最近更新 更多