HTML将文本与图像的按钮底部对齐

时间:2017-04-20 15:23:03

标签: html css text-alignment text-align

我有198px-198px的方形按钮。每个按钮下面都有一个图像和文字。由于并非所有图像都是正方形,因此我将所有图像的最大宽度和最大高度设置为128px,以便它们按比例缩放。不幸的是,我无法将文本与底部中心对齐。

我不能使用padding-top: 65px来解决其他一些SO问题,因为图像的高度可变。

我在文本的范围内尝试了position: absolute; top: 180px,但在此之后我无法将其置于中心(无法指定left: 10px,因为文本的长度可变)

感谢您的帮助。

这是一个JSFiddle https://jsfiddle.net/vbgg3keu/3/(注意:您可以扩展输出窗格的宽度,以便所有按钮在同一行上排列)

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;
}

2 个答案:

答案 0 :(得分:6)

您可以做的是将方形按钮类设置为相对位置并使用百分比来放置文本,同时将宽度跨越到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;
}

答案 1 :(得分:0)

请尝试以下代码:

.square-button {
    width: 198px;
    height: 198px;
    float: left;
    position: relative;
}
.small-img {
    max-width: 128px;
    max-height: 128px;
    position: absolute;
    top: 50%;left: 50%;
    transform: translate(-50%,-50%);
}

.button-text {
    position: absolute;
    transform: translateX(-50%);
    bottom: 10px;
    width: 100%;
    left: 50%;
}

https://jsfiddle.net/vbgg3keu/10/