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

JS_*_*ler 4 css css-position width

我正在尝试制作一个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;
}
Run Code Online (Sandbox Code Playgroud)
  <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>
Run Code Online (Sandbox Code Playgroud)

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

Roy*_*ker 6

用于width: max-content;强制绝对定位的子元素根据其内容而不是父元素的尺寸调整自身大小。

这也可以与 max-width 一起使用。

.parent {
  position: relative;
  background: #EEE;
  width: 100px;
}
.abs {
  position: absolute;
  max-width: 200px;
  width: max-content; /* this forces width: auto */
}
Run Code Online (Sandbox Code Playgroud)
  <div class="parent">
    <div>
      Div inside parent element. This will wrap at 100px.
    </div>
    <div class="abs">
      This absolutely positioned child element wraps after 200px, even though the parent's max-width is set to 100px
    </div>
  </div>
Run Code Online (Sandbox Code Playgroud)