如何防止display: table
元素超越其父元素宽度?
以下是jsFiddle以下内容:
.container {
max-width: 150px;
padding: 5px;
border: 2px solid #0f0;
}
.table {
display: table;
border: 1px solid #00f;
max-width: 100%;
}
.cell {
display: table-cell;
}
.cell:nth-child(2) {
background: #f00;
}
<div class="container">
<div class="table">
<span class="cell">
<select>
<option>long long long long long desc</option>
</select>
</span>
<span class="cell">A</span>
</div>
</div>
实际上,.table
元素比.container
宽。
如何防止这种情况并保持.table
100%父元素的最大宽度? (max-width
无效)。
我正在寻找纯CSS解决方案。
答案 0 :(得分:6)
很简单:
演示 http://jsfiddle.net/zpfLxkrh/3/
你需要两件事:
.table{
table-layout: fixed;
width: 100%;
}
select {
max-width: 100%;
}
答案 1 :(得分:4)
问题不在于您的display: table
div ...这是您的select
。
如果你想保持这个宽度,让它表现得好!
select {
width: 100%;
}
现在,选择的大小将由其单元格大小控制。我已经将单元格大小更改为50%来说明这一点。
.container {
max-width: 150px;
padding: 5px;
border: 2px solid #0f0;
}
.table {
display: table;
border: 1px solid #00f;
max-width: 100%;
}
.cell {
display: table-cell;
width: 50%;
}
.cell:nth-child(2) {
background: #f00;
}
select {
width: 100%;
}
<div class="container">
<div class="table">
<span class="cell">
<select>
<option>long long long long long desc</option>
</select>
</span>
<span class="cell">A</span>
</div>
</div>