Change the width of the div depending on the size of the maximum possible text

I want to create a button that displays different text when you hover over it. I want it to be a fixed width, but I don't know the width of the longest text, since I will use Javascript translations, and the possible content will have different lengths.

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

Here's the 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>
Run codeHide result
+4
source share
1 answer

One way is to hide the element without display:none, so do not remove it from the stream. Try the following:

.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>
Run codeHide result
+10
source

Source: https://habr.com/ru/post/1656250/


All Articles