根据最长文本的大小更改div的宽度

时间:2021-08-09 21:45:27

I want to create a button that displays a different text when you hover over it. I want it to be fixed width but I don't know the width of the longest text possible, since I'll be using Javascript translations and the possible contents are going to be be of different lengths.

我想创建一个按钮,当您悬停在它上面时,它将显示不同的文本。我希望它的宽度是固定的,但是我不知道最长的文本的宽度,因为我将使用Javascript翻译,可能的内容会有不同的长度。

Is there a way to make the button the same width as the longest text possible just with CSS?

是否有一种方法可以使按钮的宽度与CSS中最长的文本一样?

Here's a fiddle.

这是一个小提琴。

.hover-btn .hover-on,
.hover-btn:hover .hover-off {
  display: none;
}
.hover-btn:hover .hover-on,
.hover-btn .hover-off {
  display: inline;
}
<button id="myButton" class="hover-btn">
  <span class="hover-off">hey!</span>
  <span class="hover-on">click me!</span>
</button>

1 个解决方案

#1


10  

One way is hide the element without display:none so no remove it from the flow. Try this:

一种方法是在没有显示的情况下隐藏元素:没有,所以不能从流中删除它。试试这个:

.hover-btn .hover-on, .hover-btn:hover .hover-off {
  height: 0;
  display:block;
  overflow:hidden;
  visibility:hidden;
}
.hover-btn:hover .hover-on, .hover-btn .hover-off {
  height:auto;
  visibility:visible;
}
<button id="myButton" class="hover-btn">
  <span class="hover-off">hey!</span>
  <span class="hover-on">click me!</span>
</button>

#1


10  

One way is hide the element without display:none so no remove it from the flow. Try this:

一种方法是在没有显示的情况下隐藏元素:没有,所以不能从流中删除它。试试这个:

.hover-btn .hover-on, .hover-btn:hover .hover-off {
  height: 0;
  display:block;
  overflow:hidden;
  visibility:hidden;
}
.hover-btn:hover .hover-on, .hover-btn .hover-off {
  height:auto;
  visibility:visible;
}
<button id="myButton" class="hover-btn">
  <span class="hover-off">hey!</span>
  <span class="hover-on">click me!</span>
</button>