如何将文本与图片对齐放置在span标签中?

3
我使用以下HTML代码创建了一个由图像和文本组成的span元素。我想使用下面的css类使文本与图像对齐:
```html

我已经制作了一个由图像和文字组成的span元素,使用以下HTML代码。我正在尝试使用以下css类将文本与图像对齐:

```

span.my-profile {
  background-image: url('http://placehold.it/450x100/fc6');
  background-position: left center;
  background-repeat: no-repeat;
  padding-left: 16px; /* Or size of icon + spacing */
  text-align: center;
}
<span class="my-profile">My Full Name</span>

然而,这并没有像预期的那样起作用。文本仍然与图像左对齐。那么我的代码有什么问题?如何将文本居中对齐?
提前感谢。

1
你能否发布一个更完整的示例,以实际演示问题?最好是作为一个stacksnippet。另外,期望的结果是什么? - Mr Lister
3个回答

3
将背景图像添加到具有文本的同一span中只会将图像放置为带有文本的span的背景..请尝试使用<img />标记将图像作为单独元素放置在span中。然后,您可以在CSS中使用display:inline-block或float来控制图像和文本。

1
使用伪元素:before来放置图片(更改宽度,高度和边距):
span.my-profile:before {
content: "";
display: block;
background: url('/img/no-face.png') no-repeat;
width: 20px;
height: 20px;
float: left;
margin: 0 6px 0 0; }

谢谢你的帮助。但这也没有解决问题。最后,我通过在<span>中添加<img src="../img/no-face.png">作为单独的元素,并从CSS代码中删除background:标签来解决了这个问题。 - user6039980

0

尝试使用一些 宽度-高度填充display:block 属性,它会起作用。

查看这个 fiddle here

尝试使用以下 CSS 样式

span.my-profile{
  width:200px;
  height:100px;
  display:block;
  background:url(http://placehold.it/200x100) no-repeat;
  padding-top:100px;
  text-align:center;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接