HTML Align Text to Bottom of Button with Images

user2570465 picture user2570465 · Apr 20, 2017 · Viewed 7.1k times · Source

I have square buttons that are 198px-198px. Each button has an image and text underneath. Since not all images are square, I set max-width and max-height to 128px for all images so that they scale proportionally. Unfortunately, I can't align the text to the bottom center anymore.

I cannot use padding-top: 65px which solved some other SO questions because the image has a variable height.

I tried position: absolute; top: 180px in a span for the text, but I can't get it to center after that (can't just specify left: 10px because the text has variable length)

Thanks for your help.

Here is a JSFiddle https://jsfiddle.net/vbgg3keu/3/ (Note: You can expand the width of the output pane so that all the buttons line up on the same line)

HTML:

<button class="square-button">
<img class="small-img" src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"/><br/>

<span class="button-text">This text is too high</span>
</button>

<button class="square-button">
<img class="small-img" src="http://etc.usf.edu/clipart/36400/36459/ruler1_36459_lg.gif"/><br/>

<span class="button-text">This text is too high</span>
</button>

<button class="square-button">
<img class="small-img" src="https://tall.life/wp-content/uploads/2013/04/Giraffe.jpg"/><br/>

<span class="button-text">This text is the correct height</span>
</button>

<button class="square-button">
<img class="small-img" src="https://lh3.googleusercontent.com/dB3Dvgf3VIglusoGJAfpNUAANhTXW8K9mvIsiIPkhJUAbAKGKJcEMPTf0mkSexzLM5o=w300"/><br/>

<span class="button-text">This text is the correct height</span>
</button>

CSS:

.square-button {
  width: 198px;
  height: 198px;
  float: left;
}
.small-img {
    max-width: 128px;
  max-height: 128px;
}

.button-text {
  // this doesn't work because now I can't center the text
  //position: absolute;
  //top: 180px;
}

Answer

Keith picture Keith · Apr 20, 2017

What you can do is set your square-button class to position relative and use percentages to place the text while spanning the width to 100%:

https://jsfiddle.net/vbgg3keu/4/

.button-text {
  position: absolute;
  bottom: 5%;
  width: 100%;
  left: 0%;
}

.square-button {
  width: 198px;
  height: 198px;
  float: left;
  position: relative;
}