对于我的生活,我无法按照自己的意愿去做这件事。我在链接和文本范围内有一个图像。我要做的就是让图像浮动到文本的右侧,文本垂直对齐在它旁边。我无法更改标记,图像可以是任何大小,因此只使用margin-top将无效。
JS小提琴:http://jsfiddle.net/sppbe4j5/
HTML:
<div>
<a href="#">
<img src="http://placehold.it/350x150">
<span>Some Text</span>
</a>
</div>
CSS:
div{ display: table; }
a img {
display: table-cell;
float:right;
}
a {
display: table-cell;
}
a span{
vertical-align: middle;
text-align: center;
}
答案 0 :(得分:3)
您可以使用flex布局和flex order来实现这一目标:
a {
display: flex;
flex-wrap: wrap;
}
a span {
order: 1;
align-self: center;
}
a img {
order: 2;
}
<div>
<a href="#">
<img src="http://placehold.it/350x150">
<span>Some Text</span>
</a>
</div>
答案 1 :(得分:3)
实际上,只需将vertical-align: middle
提供给内联级元素img
和span
即可完成垂直对齐。
因此,真正的问题是如何在不改变HTML的情况下重新排序元素的位置。
就个人而言,如果可能的话,我会选择Flexbox布局。但是,如果支持 IE9 ,则可以使用CSS转换伪造效果。只需顺时针旋转容器并逆时针旋转单个元件,反之亦然。
<强> Example Here 强>
a.container {
display: inline-block;
transform: rotate(180deg);
text-decoration: none;
}
a.container img, a.container span {
vertical-align: middle;
display: inline-block;
transform: rotate(-180deg);
}
由于简洁而省略了Verndor前缀。
a.container {
display: inline-block;
-webkit-transform: rotate(-180deg);
-moz-transform: rotate(-180deg);
-ms-transform: rotate(-180deg);
-o-transform: rotate(-180deg);
transform: rotate(-180deg);
text-decoration: none;
}
a.container img, a.container span {
vertical-align: middle;
display: inline-block;
-webkit-transform: rotate(180deg);
-moz-transform: rotate(180deg);
-ms-transform: rotate(180deg);
-o-transform: rotate(180deg);
transform: rotate(180deg);
}
<div>
<a href="#" class="container">
<img src="http://placehold.it/350x150" />
<span>Some Text</span>
</a>
</div>
答案 2 :(得分:2)
我知道这是一个封闭的帖子,但如果有人在寻找这类问题,那么这里有另一个解决方案(比转换更好,作为接受的答案)
可以使用direction
属性反转元素的位置。然后表格布局会使它们垂直对齐:
rtl - 代表从右到左
a {
display: table;
direction: rtl;
}
a img {
vertical-align: middle;
display: table-cell;
}
a span{
vertical-align: middle;
display: table-cell;
}
&#13;
<div>
<a href="#">
<img src="http://placehold.it/350x150" />
<span>Some Text</span>
</a>
</div>
&#13;
答案 3 :(得分:0)
将其添加到范围:
a span{
line-height: 150px;
height: 150px;
}