繁体   English   中英

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

[英]HTML Align Text to Bottom of Button with Images

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

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

我试过position: absolute; top: 180px position: absolute; top: 180px文本范围内的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;
}

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

请尝试以下代码:

.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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM