how to maintain same size when the text replaces the image? | Sololearn: Learn to code for FREE!


how to maintain same size when the text replaces the image?

i have a button which has an image in it. when clicked, the image is replaced with a text. but now the button size reduces to fit the text size. how do i keep the same size for both image and text? and how to center text vertically in a button? i know this is a naive approach. But how do i go about it with <div> or any other such thing?

8/11/2022 6:38:37 PM

Harsha S

4 Answers

New Answer


You could give the button a fixed size and set the image relative to the button size (see css tab) Maybe consider toggling the image visibility/ display instead of creating an html element each time via innerHtml...


I would resize the button to be slightly larger than the dimensions of the image. And I would separate the styles.


Lisa that is great. Cleaner and responsive and the comments are informative.


Just to add more for people who prefer javascript to css The first procedure is to determine the aspect ratio (A) in respect to the image, defined A = height/width Then you need to create a fixed size for the button height or width (S), whichever axis is chosen... The other axis size could also be determine by height = S * A width = S / A This method is customizable, you can scale either the image or button without losing pixel data on the image As for the text, you just need to translate it by S*0.5 on both axes (top, left)