如何在HTML中的图像上水平和垂直居中任意文本?

时间:2015-07-07 11:40:00

标签: java html css jsp

所以我在SO上搜索了半个小时而无法找到答案。

我必须渲染图片,用户可以在其中输入字体大小,图片尺寸和信息。该消息必须在picutre上垂直和水平中心对齐。我只是无法做到正确,如果文字很短,那就没问题,但是用户可以在网址中输入任何内容(例子):

http://localhost:8080/app/slika?size=16&dim=100x200&msg=Java%20rulesfaekofakoefaeofae

后端由JSP和Java完成,这里是jsp文件的代码:

<body>
<div>
    <img src="fruits.png" width="${ width }" height="${ height }" style="vertical-align: middle">
    <%
        int centerWidth = (Integer) request.getAttribute("width") / 2;
        int centerHeight = (Integer) request.getAttribute("height") / 2;
    %>

    <span
        STYLE="position:absolute; left:<%= centerWidth/2 %>; top:<%=centerHeight %>; 
        text-align:center; font-size:${ fontSize }px; width=100%">${ message }
    </span>
</div>

你可以看到我&#34;有点&#34;硬编码,所以对于短信,显示会很好,但很长一段时间它都不会(因为文字将覆盖图像,它应该进入下一行)。

最后一句话是困扰我的,如何将文字分成下一行?我设法调整它,但不能打破它。

2 个答案:

答案 0 :(得分:0)

实际上,您可以使用CSS在任何任意大小的图像上显示任何仲裁文本(无需硬编码)。

&#13;
&#13;
.box { 
  position: relative;
  float: left;
}

.text {
  width: 100%;
  text-align: center;
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  /* Custom */
  color: red;
  font-weight: bold;
  font-size: 20px;
}
&#13;
<div class="box">
  <img src="https://placeimg.com/300/300/nature">
  <div class="text">Lorem Ipsum</div>
</div>

<div class="box">
  <img src="https://placeimg.com/300/300/nature">
  <div class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin pretium non diam vel fermentum.</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

您可以在带有display: table-cell的div中使用包含一个单元格的表格或带有display: table的div。单元格可以水平和垂直居中对齐,并具有图像背景。

以下是我的例子:http://www.kamil256.master.pl/img_center_text_example.html

CSS:

table {
    border-collapse: collapse;
    width: 400px; /* width which you get from user */
    height: 300px; /* height which you get from user */
}
td {
    background: url("cat.png") top left no-repeat;
    background-size: 100% 100%;
    font: 14px; /* font size which you get from user */
    text-align: center;
}

HTML:

<table>
    <td><!-- text which you get from user -->
        http://localhost:8080/app/slika?size=16&dim=100x200&msg=Java%20rulesfaekofakoefaeofae
    </td>
</table>