css align text in front of image

泄露秘密 提交于 2021-02-10 20:34:45

问题


I have an image and a text in front of it. the problem is, I cant align text and image, text is always in the bottom and I want it in the middle-front of image.

here is the problem:

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

回答1:


All you need to do is to add

vertical-align: middle;

to the style of .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>

The reason you are getting this issue is because by default, images are aligned to the baseline, so inorder to vertically align it to the center we use vertical-align property with a value of middle.




回答2:


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

This would do the trick :)




回答3:


The img element's bottom will be located at the same line with the text's baseline. So you can change the img's vertical-align like this:

img {
    vertical-align: -18px;
}

Fiddle here




回答4:


Heres an example

I would put the image in a container , make the container position relative and everything thats insite with position absolute, so you can position it freely.

I know this might be a bit over the top for YOUR SPECIFIC case, but in general that would help you with aligning anything

Look at my example : 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>



回答5:


in html code as folow:

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

css code as follow:

#imag
{
  background-image:imagepath/image_name.jpg;
  height:200px;
  width:200px;
  text-align:center;
}


来源:https://stackoverflow.com/questions/29646995/css-align-text-in-front-of-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!