[英]Align text vertically next to image with CSS
我想将所有文本和图像垂直居中对齐。 我该怎么做呢? 因此,基本上, Hello
出现在每个图像的中间,并且第一个图像垂直居中。
演示: http : //jsfiddle.net/ueqba2zf/
div { width:75px; height:100px; float:left; background:#eee }
<div><img src="http://placehold.it/25x25"> Hello</div> <div><img src="http://placehold.it/25x100"> Hello</div>
我已经有一段时间没有做HTML了,但是这样的事情应该可以工作:
<div style="display=block;float:left"><img src="http://placehold.it/25x25" style="height=80px"> <p style:"text-align: center;;width 75px;">Hello</p></div>
您可以看一下:
这是一个主意,尽管它不是最好的。 除非您有合理的方法来预期图像大小,否则它可能不切实际。 但是,我认为,如果没有这些知识或对象周围没有一致的包装,这将是不可能的。
的HTML
<div class="img-wrap">
<img class="small-img" src="http://placehold.it/25x25" />
<span class="text">Hello</span>
</div>
<div class="img-wrap">
<img class="large-img" src="http://placehold.it/25x100" />
<span class="text">Hello</span>
</div>
的CSS
.img-wrap img {
float: left;
}
.img-wrap img + .text {
display: inline-block;
float: left;
height: 1em;
margin-top: -.5em;
white-space: nowrap;
}
.small-img + .text {
transform: translateY(12.5px);
}
.large-img + .text {
transform: translateY(50px);
}
更新的小提琴
基本上,我要做的只是将文本2限制在一行内,以便可以预测其高度,然后将其平移为相对于上一个图像的高度居中。
如果您不只需要一行文本,可以执行以下操作:
的HTML
<div class="box small-box">
<img class="small-img" src="http://placehold.it/25x25" />
<span class="text">Hello There</span>
</div>
<div class="box large-box">
<img class="large-img" src="http://placehold.it/25x100" />
<span class="text">Hello There</span>
</div>
的CSS
.box {
float: left;
position: relative;
}
.small-box {
height: 25px;
}
.large-box {
height: 100px;
}
.box img + .text {
position: absolute;
display: block;
top: 0;
bottom: 0;
right: 0;
height: 2.2em;
line-height: 1.1;
margin: auto 0;
overflow: hidden;
}
.box .small-img + .text {
left: 25px;
transform: none;
}
.box .large-img + .text {
left: 25px;
transform: none;
}
在这里,我实际上是使用带有自动边距的绝对位置来使文本居中。 您需要正确设置包装器的大小,并限制可见文本的数量,但这还不错。 另外,考虑使用jQuery省略号之类的工具来处理文本溢出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.