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