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

标签 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/ (注意:您可以扩展输出 Pane 的宽度,以便所有按钮都排在同一行上)

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

最佳答案

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

关于HTML 将文本与带图像的按钮底部对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43523729/

相关文章:

html - CSS Flexbox - 正确对齐单元格列

html - 是否可以重新定义屏幕视口(viewport)或具有 "not-so-to-the-right"固定对齐元素?

html - CSS:居中对齐文本,同时将容器的其他元素保持在左侧

ios - UILabel 不能同时包裹和对齐

html - 将 H1 对齐到 DIV 的右下角

javascript - 媒体上的导航无法获得 100% 的宽度

javascript - 使用 knockout.js 如何刷新 Select 元素中的可观察数组

jquery - 将 <img> 添加到 div 标签

javascript - 当按钮为空时,按钮尺寸会变得太小

css - Compass SCSS/SASS 的导入 compass/重置顺序