是否有可能修复元素的width
(或min-width
)等于该元素填充特定内容的时间?
示例:用于选择月份的按钮可以包含1月,2月等文本。我希望按钮始终为宽度,就好像文本是9月(最长的字符串,可视化)。目前发生的情况是,如果当前选择是五月或七月,按钮非常小,那么当选择是十一月或九月时按钮会更大,此外,这可以改变其他元素的布局。
当然,我可以使用像素,或百分比,或width
等设置min-width
或vw
- 但考虑到设备,屏幕,用户控制缩放或字体大小的广度,唯一安全的方法是猜测大小是可能远远超过实际需要,这本身看起来很糟糕并且是不可取的。
设置一个兄弟div
与visibility: hidden
是关键,两者都驻留在另一个容器div
。
Codepen在这里:https://codepen.io/anon/pen/XQxeep
let strings = [
'tiny', 'short', 'medium-length', 'this is a long string',
'finally, an extremely long string'
];
let m = 0;
function nextString() {
m = (m == 4) ? 0 : m + 1;
document.getElementById('bt').innerHTML=strings[m]
}
button {
display: inline-block;
position: relative;
}
.showme {
position: absolute;
left: 0px;
right: 0px;
}
.hideme {
visibility: hidden;
}
this is the button we are trying to keep a fixed size, the size of the longest element so it will not expand:
<button onclick="nextString()">
<div class="outer">
<div class="showme" id="bt">tiny</div>
<div class="hideme">finally, an extremely long string</div>
</div>
</button>