我正在尝试拉伸一个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>
由于在绝对元素的宽度计算中考虑了父元素的填充,因此您可以向父元素添加更多的填充:
.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>
这是有点通过将abs
包装在一个比relative
父级宽得多的绝对div中解决的。现在,问题变成了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">
< 200px shrinks to fit.
</div>
</div>
</div>
您可以使用'!important'替代(不推荐使用)
.parent {
position: relative;
background: #EEE;
width: 100px;
}
.abs {
position: absolute;
max-width: 200px;
width: 200px !important;
}
.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>