首页 > 解决方案 > 忽略父级最大宽度 css

问题描述

我的网站上有一个容器,可以将所有内容保持在一定宽度内,就像这样..

HTML

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

CSS

.container{
   max-width: 1300px
}

现在我有一个 div,我想忽略最大宽度并扩展到边缘,但我不希望它被绝对定位并从网站的流程中取出,所以我这样做了..

HTML

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

CSS

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

所以这给了我正确的宽度,但它仍然遵循父容器的最大宽度,而不是从窗口的左边缘开始,但是父容器的边缘现在我可以给它一个负边距但是..因为窗口宽度变化负边距并不总是正确的..我怎样才能解决这个问题而不使其成为绝对元素?

谢谢

标签: htmlcss

解决方案


子元素默认左对齐。

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

您可以尝试将其居中:

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

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

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

然后你可以做的是从左边居中(左边距:50%):

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

如果您现在将子元素的 X 轴向左变换 50% ( x - 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>


推荐阅读