html - 在图像上居中文本

标签 html css

这可能很容易做到,但出于某种原因,我没有任何效果。比方说我有一个图像和一个像这样的文本:

<div id="my_div">
    <img src="my_img.png" alt="Test" />
    <p>Some Text</p>
</div>

如何将文本 Some Text 在我的图像上水平和垂直居中(我希望文本出现在图像的中间)

谢谢

最佳答案

你可以使用display: table/table-cell:

CSS:

.example {
    display: table;
    width: 100px; /* Width of the image */
    height: 100px; /* Height of the image */
}

.example > P {
    background: url(my_img.png) no-repeat;
    display: table-cell;
    text-align: center; /* Center text horizontally. */
    vertical-align: middle; /* Center text vertically. */
}

HTML:

<div class="example"><p>
    Some text
</p></div>

如果您需要将图像作为 IMG 元素,您可以使用类似的代码,在它之前添加 IMG 元素和负数 margin-top 用于带有 display:table 的元素,用于将文本定位在图像上方。

关于html - 在图像上居中文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12850086/

相关文章:

javascript - jQuery动画批量图像

html - 尝试调整我的 Logo 的大小并在不调整导航栏大小的情况下在 Logo 的侧面添加标题

javascript - 将数据从 Controller 传递到 JavaScript

jQuery 动态调整元素及其内容 onClick

html - 将 h1 置于标题中心?

jquery - Superfish 下拉列表被表格边界截断

css - 相对定位DIV?

html - 打破这些界限的语义正确方法是什么?

css - 如何在列表中的文本之前对齐伪标记?

css - responsive.css 中媒体的新属性无效