【问题标题】:How to horizontally and vertically center arbitary text over an image in HTML?如何在 HTML 中的图像上水平和垂直居中任意文本?
【发布时间】:2015-07-07 11:39:59
【问题描述】:

所以我在SO中搜索了半个小时,找不到答案。

我必须在用户可以动态输入字体大小、图片尺寸和消息的地方渲染图片。该信息必须在图片上垂直和水平居中对齐。我只是无法正确理解,如果文本很短也没关系,但用户可以在 URL 中输入任何内容(示例):

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>

您可以看到我“有点”对其进行了硬编码,因此对于短消息显示会很好,但长时间不会显示(因为文本会覆盖图像,并且应该进入下一行)。

最后一句话让我很困扰,如何将文本分成下一行?我设法对齐它,但无法打破它。

【问题讨论】:

  • + 请添加JSFiddle,对您和我们都有很大帮助。
  • @Sidsec9 这是一个jsp文件,不是php。

标签: java html css jsp


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您可以在带有 display: table 的 div 中使用带有一个单元格的表格或带有 display: table-cell 的 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-18
      • 2013-07-23
      • 2015-09-25
      • 1970-01-01
      • 2012-05-04
      • 1970-01-01
      相关资源
      最近更新 更多