This question already has answers here:
How to prevent child's content from stretching parent's width
                                
                                    (1个答案)
                                
                        
                        
                            How to match width of text to width of dynamically sized image? [duplicate]
                                
                                    (3个答案)
                                
                        
                                在4个月前关闭。
            
                    
在计算父元素的宽度时,是否可以通过CSS告诉浏览器忽略某个元素?具体来说,在Flex布局中?

例如,这看起来不错:



<div style="display: inline-flex; flex-direction: column; background-color: #ccc; padding: 1rem">
  <h1>Width set by heading</h1>
  <div style="border: 1px solid red; padding: 0.5rem; background-color: #fff; color: red">short text</div>
  <label>Email</label>
  <input type="text" />
  <button type="button" style="align-self: center">Submit</button>
</div>





但是,当红色区域增长到大于标题的宽度时,整个<div>的宽度将扩大:



<div style="display: inline-flex; flex-direction: column; background-color: #ccc; padding: 1rem">
  <h1>Width set by heading</h1>
  <div style="border: 1px solid red; padding: 0.5rem; background-color: #fff; color: red">This text is much longer and causes the width of the div to expand.</div>
  <label>Email</label>
  <input type="text" />
  <button type="button" style="align-self: center">Submit</button>
</div>





有没有办法告诉浏览器使红色区域延伸到父区域的宽度,但是在计算必要的宽度时忽略其自身的宽度?像这样的东西,但是没有所有的手动<br>标签,或强制使用特定的宽度:



<div style="display: inline-flex; flex-direction: column; background-color: #ccc; padding: 1rem">
  <h1>Width set by heading</h1>
  <div style="border: 1px solid red; padding: 0.5rem; background-color: #fff; color: red">This text is much longer but is contained<br />within the parent width.</div>
  <label>Email</label>
  <input type="text" />
  <button type="button" style="align-self: center">Submit</button>
</div>

最佳答案

不适用于flexbox,但还有另一个宽度display:table



.parent {
  display: table;
  width: 1%;
}

h1 {
  white-space: nowrap;
}

<div class="parent" style="background-color: #ccc; padding: 1rem">
  <h1>Width set by heading</h1>
  <div style="border: 1px solid red; padding: 0.5rem; background-color: #fff; color: red">This text is much longer but is contained within the parent width.</div>
  <label>Email</label>
  <input type="text" />
  <button type="button">Submit</button>
</div>

08-25 13:39
查看更多