【问题标题】:Expanding a child div outside of a container div equally on boths sides with margin: 0 auto将子 div 扩展到容器 div 外的两边,边距:0 auto
【发布时间】:2015-06-26 14:05:04
【问题描述】:

假设我有一个包含子 div 的 div。容器 div 设置为margin: 0 auto,因此当宽度增加时,div 会在两侧展开。如果这个容器内的 div 也设置为margin: 0 auto,有没有办法让这个 div 扩展到它的容器 div 之外,并且左右相等?

下面的例子展示了当.background的宽度增加超过容器的宽度时,它的大小只从右侧增加,而不是从两侧增加。

css和html:

.container {
  width: 600px;
  background-color: lightgreen;
  margin: 0 auto;
}
.background {
  width: 300px;
  margin: 0 auto;
  background-color: blue;
}
.content {
  width: 200px;
  background-color: lightblue;
  margin: 0 auto;
}
<div class = "container">
  <div class = "background">
    <div class = "content">
      content
    </div>
  </div>
</div>

http://jsfiddle.net/DpYGm/2/

这一切都是为了让横幅图形背景图像跨越页面的正文宽度,但仍然使页面内部的内容保持不变。

【问题讨论】:

  • 所以您希望div.background 成为页面的全宽?即使它是宽度为 600px 的包含块 div.container 的子代?
  • 为什么不把背景图片放在div.container上?
  • @MarcAudet 这不能解决我的问题。我不想更改父元素的 css。
  • 不要为边界容器设置宽度。以 min-width 为起点,然后让它随内容浮动。

标签: html css


【解决方案1】:

假设您希望background div 在每一侧突出 50 像素。您可以在 CSS 中执行此操作:

.background {
    margin: 0 -50px 0 -50px;
    background-color: #00F;
}

一个完整的例子:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">

    <style media="all">

      .container {
        width: 500px;
        background-color: lightgreen;
        margin: 0 auto;
        height: 400px; /* for illustration */
      }
      .background {
        margin: 0 -50px;
        background-color: blue;
      }
      .content {
        width: 200px;
        background-color: lightblue;
        margin: 0 auto;
      }

    </style>

  </head>
  <body>

    <div class = "container">
      <div class = "background">
        <div class = "content">
          content
        </div>
      </div>
    </div>

  </body>
</html>

【讨论】:

  • 在 Chrome 中就像一个魅力。我将在我的网页上测试这个答案,然后在几个浏览器中回复你。
  • 酷。它非常防弹,我想你会发现的。 :-)
  • 太棒了。适用于 IE7、8、9、Chrome、Firefox、Safari。
【解决方案2】:

肯定的:

.container {
    width: 600px;
    background-color: #eee;
    margin: 0 auto;
    padding: 10px 0;
}
.background {
    width: 400px;
    margin: 0 auto;
    background-color: blue;
    padding: 10px 0;
}
.content {
    width: 500px;
    background-color: red;
    margin-left: -50px;
}

http://jsfiddle.net/yBcpu/1/

【讨论】:

    【解决方案3】:

    根据您的推理,有一种更语义化的方式来实现这一点:

    .container {
        background: green url(../path-to-image.jpg) no-repeat top center;
        margin: 0 auto;
        min-height:300px;
    }
    
    .content {
        width: 500px;
        background-color: red;
        margin: 0 auto;
        min-height: 300px;
    }
    

    将背景图片粘贴在 .container 上,位置居中。

    http://jsfiddle.net/DpYGm/5/

    【讨论】:

      猜你喜欢
      • 2011-10-15
      • 2012-10-02
      • 1970-01-01
      • 2015-09-13
      • 2013-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-16
      相关资源
      最近更新 更多