绝对div是否可以具有width:auto,并且还忽略其父级的宽度?

时间:2019-12-20 22:27:38

标签: css width css-position

我正在尝试制作一个div来拉伸以适合其内容,直到最大宽度,然后再包装内容。

使用绝对定位的div可以正常工作-除非其父级的宽度受到限制。当其父级的宽度受到限制时,绝对定位的div的作用就好像其max-width是其父级的width

从本质上讲,我希望绝对定位的div“假装”其父对象具有100%的宽度,并在尊重max-width的同时给我很好的“伸缩适应”行为我开始吧。

在下面的示例中,我希望第一个.abs工作,即使它是“瘦” div的孩子。

.parent {
  position: relative;
  background: #EEE;
  width: 100px;
}
.abs {
  position: absolute;
  max-width: 200px;
  /* width:  auto, but ignore parent! */
}

.parent2 {
  margin-top: 150px;
  background: rgba(0,128,0,.1);
  width: 100px;
}
  <div class="parent">
    <div>
      Doesn't work.
    </div>
    <div class="abs">
      This wraps after 100px, because it's parent has 100px width.
    </div>
  </div>
  
  <div class="parent2">
    <div>
      Does work.
    </div>
    <div class="abs">
      This wraps at 200px, because it's parent is as wide as the viewport, so it honors the max-width of 200px.
    </div>
  </div>

https://jsfiddle.net/nqws2p09/1/

2 个答案:

答案 0 :(得分:0)

由于在绝对元素的宽度计算中考虑了父元素的填充,因此您可以向父元素添加更多填充:

.parent {
  position: relative;
  background: #EEE content-box; /* Color only the content */
  width: 100px;
  padding-right:200px;
  margin-right:-200px; /*to consume the padding added*/
}
.abs {
  position: absolute;
  max-width: 200px;
}

.parent2 {
  margin-top: 150px;
}
<div class="parent">
    <div>
      Does work.
    </div>
    <div class="abs">
      This wraps after 100px, because it's parent has 100px width.
    </div>
  </div>
  
  <div class="parent parent2">
    <div>
      Does work.
    </div>
    <div class="abs">
      This wraps at 200px, because it's parent is as wide as the viewport, so it honors the max-width of 200px.
    </div>
  </div>

答案 1 :(得分:0)

这是某种解决方案,方法是将abs包装在一个绝对div中,该div的宽度比relative父级的宽度宽得多。现在,问题变成了wrapper的大小以延伸到视口的右侧,这是另一个问题的主题。

.parent {
  position: relative;
  background: #EEE content-box; /* Color only the content */
  width: 100px;
}
.abs-wrapper {
  position: absolute;
  width: 800px;
}
.abs {
  position: absolute;
  max-width: 200px;
  border: 1px solid gray;
}
  <div class="parent">
    <div>
      Doesn't work.
    </div>
    <div class="abs-wrapper">
      <div class="abs">
        This correctly wraps after 200px, because it's parent is a wrapper with a very large width. Thus, this div will stretch-to-fit, and also honor max-width.
      </div>
    </div>
  </div>
  
  
    <div class="parent" style="margin-top: 150px">
    <div>
      Doesn't work.
    </div>
    <div class="abs-wrapper">
      <div class="abs">
        &lt; 200px shrinks to fit.
      </div>
    </div>
  </div>

https://jsfiddle.net/rxwqtpsz/