How to dynamically adjust button width based on text length in CSS? | XM Community
Skip to main content
Solved

How to dynamically adjust button width based on text length in CSS?

  • June 29, 2023
  • 4 replies
  • 5672 views

JohannesCE
Level 6 ●●●●●●
Forum|alt.badge.img+12

Hello community! I use the following CSS code to style the next and previous buttons in a survey. Right now, I just look if the text fits the button in the mobile version and then adjust the width of the box.

The problem is that the survey is in several languages and some translations of “next” are longer than others.

I would like the box containing the "next" and "previous" text to dynamically adjust according to the lenght of the largest text. For example, "previous" has 8 characters, and "next" 4. So both buttons should be large enough to fit 8 characters. How do I do this?

/* Style next&previous buttons */
.Skin #Buttons #NextButton,
.Skin #Buttons #PreviousButton {
text-align: center !important;
padding: 0px !important;
width: 25% !important;
height: 50px !important;
border-radius: 16px !important; /* rounding */
font-weight: bold;
font-size: 16px !important;
}
#NextButton,
#PreviousButton {
background-color: #30B3AF !important;
color: #fff !important;
}
#NextButton:hover,
#NextButton.q-checked,
#NextButton:focus,
#PreviousButton:hover,
#PreviousButton.q-checked,
#PreviousButton:focus {
background-color: #FFCF2E !important;
color: #192743 !important;
}

 

Best answer by Deepak

@JohannesCE Try changing width to 

width: max-content !important;

This should dynamically change the width.

4 replies

Deepak
QPN Level 8 ●●●●●●●●
Forum|alt.badge.img+46
  • 1555 replies
  • Answer
  • June 29, 2023

@JohannesCE Try changing width to 

width: max-content !important;

This should dynamically change the width.


JohannesCE
Level 6 ●●●●●●
Forum|alt.badge.img+12
  • Author
  • Level 6 ●●●●●●
  • 144 replies
  • June 29, 2023

Hi @Deepak, thanks! The problem is that this way you get two buttons of different sizes. The butoons should be of the same size, i.e. that of the one with most characters. In this case I need the Next button to take the size of the Previous button:

 


JohannesCE
Level 6 ●●●●●●
Forum|alt.badge.img+12
  • Author
  • Level 6 ●●●●●●
  • 144 replies
  • June 29, 2023

O actually, I think it could be as easy as:

min-width: 100px !important;


Deepak
QPN Level 8 ●●●●●●●●
Forum|alt.badge.img+46
  • 1555 replies
  • June 29, 2023

There could be a longer route as well where you compare the length and assign the larger one to both.

Hope it helps!