居中左边距但右边距 100% 的视口(到最后)

Center left margin but right margin 100% of viewport (to the end)

我遇到了一个很难解决的问题。

基本上,我希望 div 从 margin 0 auto 的左侧位置开始,并在视口边缘结束。请参阅下图以帮助说明这一点。

HTML 的基本内容是...

<div style="max-width:500px; margin: 0 auto;">
  <div> <!-- needs to start at left margin and stretch to 100% of viewport -->
    <ul>
     <li></li>
    </ul>
   </div>
</div>

如有任何帮助,我们将不胜感激!

谢谢

是的,这是完全可以实现的。但是,在使用 calc 之前,请记住它是 CSS 3 并且附带 some usability limitations(没有 IE8,没有 Opera Mini)。

.container {
  max-width: 500px;
  margin: 0 auto;
}
.container > div {
  margin-top: 20px;
  min-height: 200px;
  background-color: #ccc;
}
.container > div > ul {
  width: 100%;
  margin: 0;
  padding: 0;
}
.container > div > ul > li {
  padding: 10px;
  list-style-type: none;
}
.container > div > ul > li:nth-child(2) {
  width: calc(((100vw - 100%) / 2) + 100%);
  background-color: red;
  min-height: 30px;
  color: white;
  box-sizing: border-box;
  text-align: right;
}
<div class="container">
  <div>
    <!-- needs to start at left margin and stretch to 100% of viewport -->
    <ul>
      <li>first li</li>
      <li>second li</li>
    </ul>
  </div>
</div>

大部分CSS是为了让它看起来像你的照片。但是模型是:

.grand-parent {
    width: {some-fixed-width}; // 500px in our case
    margin: 0 auto;
    position: relative;
    padding-left: 0;
    padding-right: 0;
}
.parent {
    width: 100%;
    padding-left: 0;
    padding-right: 0;
    margin-left: 0;
    margin-right: 0;
}
.child {
    width: calc(((100vw - 100%) / 2) + 100%);
    box-sizing: border-box;
    margin-left: 0;
    margin-right: 0;
}

其中一些甚至没有出现在我上面的代码中,因为它们是默认值,但它们对于它的工作很重要。如果您决定在父级上使用一些填充,则必须在子级中补偿它,无论是在计算中(100% 变为 100% + left-padding of parent + right-padding-of-parent)还是在左侧保证金(negative left margin of parent)。但是,为了简单起见,不要在父级上使用左右边距或填充。 :))

jsFiddle here.

参见示例:jsFiddle

HTML:

<div class="abc">
  <div class="new">
    <ul>
      <li>123</li>
    </ul>
  </div>
</div>

CSS:

.abc{width:500px; margin: 0 auto; background:#ccc; overflow:hidden; height:500px;}
.new{width:100%; background:#ff0000;}

您可以使用以下代码:

<div class="container" style="position: relative; border: 1px solid orange; min-height:200px;">
<div style="max-width: 600px; margin: 0 auto;border: 1px solid red;">
  <div style="border: 1px solid blue;position: absolute;right: 0;width: calc(100% - 300px);"> <!-- needs to start at left margin and stretch to 100% of viewport -->
  test data
    </div>
</div>
</div>

但仍然无法实现。您将不得不使用 javascript 来计算需要放置在视口右侧位置的 div 的宽度。应用 position absolute 和 right 0 会将其向右移动。只是需要处理宽度计算。