QOI QOI - 2 months ago 7
HTML Question

Change width of div depending on size of longest possible text

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.

Is there a way to make the button the same width as the longest text possible just with 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>




Answer

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>

Comments