Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change width of div depending on size of longest possible text

Tags:

html

css

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>
like image 341
QOI Avatar asked Dec 25 '22 01:12

QOI


1 Answers

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>
like image 78
DaniP Avatar answered Feb 01 '23 12:02

DaniP