忽略父最大宽度CSS

时间:2018-07-30 05:20:21

标签: html css

我的网站上有一个容器,可以将所有内容保持在一定宽度内。

HTML

<div class="container">
// content in here
</div>

CSS

.container{
   max-width: 1300px
}

现在我有一个div,我想忽略最大宽度并扩展到边缘,但是我不希望它被绝对定位并从网站流中删除,所以我这样做了。 / p>

HTML

<div class="extend-past">
   // content here
</div>

CSS

.extend-past{
   width: 100vw;
   height: 200px;
}

所以这给了我正确的宽度,但是它仍然遵循父容器的最大宽度,而不是从窗口的左边缘开始,但是现在我可以给它一个负的余量。 ..因为窗口的宽度会改变,所以负边距不会总是正确的..如何在不使其成为绝对元素的情况下解决这个问题?

谢谢

1 个答案:

答案 0 :(得分:6)

子元素默认为左对齐。

-------------
|-----      |
-------------

您可以尝试将其居中:

-------------
|   -----   |
-------------

但是如果一个元素太大,它会停留在左边:

-------------
|-----------|---------
-------------

然后您可以做的就是将其从左居中(左边缘:50%):

-------------
|     ------|--------------
-------------

如果现在将子元素的X轴向左(x-50)变换50%,则会得到以下信息:

    --------------
----|------------|----
    --------------

.container {
  background-color: green;
  margin: 0 auto;
  max-width: 50%;
  padding: 10px;
}

.container > div {
  width: 80%;
  height: 50px;
  margin: 5px auto;
  background-color: red;
}

.container > div.overflow {
  width: 150%;
}

.solution .overflow {
  transform: translateX(-50%);
  margin-left: 50%;
}
<!-- Problem situation -->
Problem situation:
<div class="container">
  <div>
    Item 1
  </div>
  <div class="overflow">
  Item 2
  </div>
</div>

<!-- Solution -->
Solution:
<div class="container solution">
  <div>
    Item 1
  </div>
  <div class="overflow">
  Item 2
  </div>
</div>

相关问题