[英]Prevent text from wrapping in an absolutely positioned element
我想創建一個意見箱,但“下拉列表”中的項目會自動換行。 我希望他們在水平方向上占據所需的空間。
我如何告訴菜單在水平方向上占用其子菜單所需的空間?
.container { position: relative; width: 200px; } .container > input { box-sizing: border-box; width: 100%; } .menu { position: absolute; border: 1px solid blue; padding: 2px; }
<div class="container"> <input type="text"> <div class="menu"> <span class="item">a very very very very long item</span> </div> </div>
和jsfiddle: https ://jsfiddle.net/89d2z95t/6/
絕對定位的元素具有一個邊界框,該邊界框由最近定位的祖先( MDN )設置。 流出要素受這些邊界的限制。
在您的代碼中,由於最接近的祖先( .container
)具有200px的固定寬度,因此絕對定位的后代( .menu
)不能超過該限制。 因此,文本換行。
您可以強制元素使white-space: nowrap
框溢出white-space: nowrap
。
.container { position: relative; width: 200px; } .container>input { box-sizing: border-box; width: 100%; } .menu { position: absolute; border: 1px solid blue; padding: 2px; white-space: nowrap; /* NEW */ }
<div class="container"> <input type="text"> <div class="menu"> <span class="item">a very very very very long item</span> </div> </div>
在您的.container
您可以指定min-width: 200px;
而不是絕對寬度,這將使其與孩子一起水平伸展。
然后,為了防止更大的跨度,您可以強制使其永不環繞:
.item {
white-space: nowrap;
overflow: hidden;
}
更新到您的jsfiddle,設置輸入width:200px
.container { position: relative; } .container > input { box-sizing: border-box; width:200px; } .menu { position: absolute; border: 1px solid blue; padding:2px; }
<div class="container"> <input type="text"> <div class="menu"> <span class="item">a very very very very long item</span> </div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.