css在图像前对齐文本

问题描述 投票:1回答:5

我前面有图像和文字。问题是,我无法使文本和图像对齐,文本始终在底部,而我希望它在图像的中间位置。

这里是问题:

    .imgf{
     width:45px;
    }
    .textf{
     margin-left:2px;
    }
<img src=https://upload.wikimedia.org/wikipedia/commons/thumb/e/e3/Nuvola_wikipedia_icon.png/240px-Nuvola_wikipedia_icon.png class=imgf> <span class=textf>comments(20)</span>
html css vertical-alignment
5个回答
4
投票

您要做的就是添加

vertical-align: middle;

。imgf的样式

.imgf {
  width:45px;
  vertical-align: middle;
}
.textf {
  margin-left:2px;
}
<img src=https://upload.wikimedia.org/wikipedia/commons/thumb/e/e3/Nuvola_wikipedia_icon.png/240px-Nuvola_wikipedia_icon.png class=imgf> <span class=textf>comments(20)</span>

您遇到此问题的原因是,默认情况下,图像与baseline对齐,因此为了将其垂直对齐至中心,我们使用vertical-align属性,其值为middle


1
投票
.imgf{
 width:45px;
    float:left;
}
.textf{
 margin-left:2px;
}

这可以解决问题:)


1
投票

img元素的底部将与文本基线位于同一行。因此,您可以像这样更改imgvertical-align

img {
    vertical-align: -18px;
}

Fiddle here


0
投票

这里有个例子

我将图像放入容器中,使容器位置相对,并且所有在位的东西都保持绝对位置,因此您可以自由地放置它。

我知道这可能会超出您的特定情况,但总的来说,这将帮助您调整所有内容

看我的例子:http://codepen.io/anon/pen/LEwQdB

<style>
div{
  width:200px;
  height:200px;
  position:relative;
  background-color:green;
}
div img{
  background-color:red;
  width:180px;
  height:180px;
  position:absolute;
  display:block;
  left:50%;
  margin-left:-90px;
  margin-top:-90px;
  top:50%;
}
div span{
  position:absolute;
  background-color:white;
  width:100%;
  text-align:center;
  color:black;
  top:50%;
  margin-top:-10px;
}
</style>
<div>
  <img src="#"/>
  <span>title</span>
</div>

0
投票

在html代码中如下:

<div id="imag">
  you text here
 </div>

css代码如下:

#imag
{
  background-image:imagepath/image_name.jpg;
  height:200px;
  width:200px;
  text-align:center;
}
© www.soinside.com 2019 - 2024. All rights reserved.