CSS-固定元素的宽度设置为特定的内部内容?

时间:2019-04-22 07:34:05

标签: html css width

是否可以将元素的width(或min-width)固定为等于该元素填充特定内容的时间?

示例:用于选择月份的按钮可以包含一月,二月等文本。我希望按钮始终的宽度就像文本是九月(最长的字符串,从视觉上看)。当前发生的情况是,如果当前选择为5月或7月,则按钮会很小,而当11月或9月为选择时,按钮会变得更大,进而会更改其他元素的布局。

当然,我可以使用像素或百分比或width等来设置min-widthvw,但要考虑到设备,屏幕,用户对缩放或字体大小,唯一安全的方法是猜测一个可能比实际所需的大小大得多的大小,该大小本身看起来很糟糕并且不受欢迎。

1 个答案:

答案 0 :(得分:0)

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>