且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-11-02 13:02:17

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

.box {position:relative; float:left;}。text {width:100%; text-align:center;位置:绝对;左:0;顶部:50%; transform:translateY(-50%); / *自定义* /颜色:红色; font-weight:bold; font-size:20px;}

< div class = 框 &GT; < 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>

So I've searched through the SO for half an hour and couldn't find answer.

I have to render picture where user can dinamically enter the font size, picture dimension and message. That message has to be vertically and horizontally centrally aligned over the picutre. I just can't get it right, it would be ok if the text is short, but user can enter anything in URL (example):

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

Back-end is done by JSP and Java, here is the code of jsp file:

<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>

You can see that I "kinda" hardcoded it, so for short messages the display will be fine, but for long it won't (as the text will go over the image, and it should break into next line).

That last sentence is what is bothering me, how to break text into the next line? I managed to align it, but can't break it.

You can actually just use CSS to display any arbitary text over any arbitary size of image (without hardcoding).

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