我正在尝试设置div的宽度,并且它的内容为其中段落user-title
的宽度。这是HTML和CSS:
.panel {
margin-bottom: 20px;
width: auto;
display: inline-flex;
flex-direction: column;
box-shadow: 0 2px 4px 0 #C6C2BF;
padding: 0.5rem 1rem 1rem;
}
.user-title {
display: flex;
}
.panel>div {
display: flex;
flex-direction: column;
}
.panel>div>p {
display: flex;
flex-grow: 1;
width: 0;
}
<div class="panel">
<p class="user-title">Date 08.03.2018 User: Joe Doe</p>
<div>
<p>Some long text in the paragraph that is wider than the title above it</p>
<p>Another shorter text</p>
</div>
</div>
这种设置使得元素占据user-title
元素的宽度,但是,文本分成多行。我怎样才能解决这个问题?
这是fiddle。
答案 0 :(得分:5)
如果我在这里并没有完全弄错,那么使用CSS跨越浏览器的唯一方法是将display: inline-block
与display: table-row
/ display: table-caption
合并。
Stack snippet
.panel {
margin-bottom: 20px;
display: inline-block;
box-shadow: 0 2px 4px 0 #C6C2BF;
padding: 0.5rem 1rem 1rem;
}
.user-title {
display: table-row;
}
.panel > div {
display: table-caption;
caption-side: bottom;
}
&#13;
<div class="panel">
<p class="user-title">Date 08.03.2018 User: Joe Doe</p>
<div>
<p>Some long text in the paragraph that is wider than the title above it</p>
<p>Another shorter text</p>
</div>
</div>
&#13;
如果您不关心IE,请使用width: 0; min-width: 100%;
上的.parent div
。
注意,我在Edge v.16,Firefox v.58和Chrome v.64上成功测试了这一点,但是如果它适用于Safari我就不能说了。
Stack snippet
.panel {
margin-bottom: 20px;
display: inline-flex;
flex-direction: column;
box-shadow: 0 2px 4px 0 #C6C2BF;
padding: 0.5rem 1rem 1rem;
}
.panel > div {
width: 0;
min-width: 100%;
}
&#13;
<div class="panel">
<p class="user-title">Date 08.03.2018 User: Joe Doe</p>
<div>
<p>Some long text in the paragraph that is wider than the title above it</p>
<p>Another shorter text</p>
</div>
</div>
&#13;
更新
经过一些反复试验后,我在IE11和Edge / Firefox / Chrome
上都有了这个功能Stack snippet
.panel {
margin-bottom: 20px;
display: inline-flex;
flex-direction: column;
box-shadow: 0 2px 4px 0 #C6C2BF;
padding: 0.5rem 1rem 1rem;
}
.panel > div {
width: 0;
min-width: 100%;
display: flex; /* for IE11 */
flex-wrap: wrap; /* for IE11 */
}
.panel > div > p {
flex: 100%; /* for IE11 */
}
&#13;
<div class="panel">
<p class="user-title">Date 08.03.2018 User: Joe Doe</p>
<div>
<p>Some long text in the paragraph that is wider than the title above it</p>
<p>Another shorter text</p>
</div>
</div>
&#13;