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

+4

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? https://code.sololearn.com/W6UXJZ3Ou6bu/?ref=app 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

+8

You could give the button a fixed size and set the image relative to the button size (see css tab) https://code.sololearn.com/WhMoU74kaS4w/?ref=app Maybe consider toggling the image visibility/ display instead of creating an html element each time via innerHtml...

+4

I would resize the button to be slightly larger than the dimensions of the image. And I would separate the styles. https://code.sololearn.com/WSbmGY1KsxvE/?ref=app

+4

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

+4

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 https://en.wikipedia.org/wiki/Aspect_ratio 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)